我的Hibernate Search分析器配置存在一些问题。 我的一个索引实体(" Hospital")有一个String字段(" name"),其中包含长度为1-40的值。我希望能够通过搜索一个字符找到一个实体(因为有可能,医院有单个字符名称)。
@Indexed(index = "HospitalIndex")
@AnalyzerDef(name = "ngram",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = StandardFilterFactory.class),
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = NGramFilterFactory.class,
params = {
@Parameter(name = "minGramSize", value = "1"),
@Parameter(name = "maxGramSize", value = "40")})
})
public class Hospital {
@Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO, analyzer = @Analyzer(definition = "ngram"))
private String name = "";
}
如果我添加名为"我的测试医院" Lucene索引看起来像这样:
1 name al
1 name e
1 name es
1 name est
1 name h
1 name ho
1 name hos
1 name hosp
1 name hospi
1 name hospit
1 name hospita
1 name hospital
1 name i
1 name it
1 name ita
1 name ital
1 name l
1 name m
1 name my
1 name o
1 name os
1 name osp
1 name ospi
1 name ospit
1 name ospita
1 name ospital
1 name p
1 name pi
1 name pit
1 name pita
1 name pital
1 name s
1 name sp
1 name spi
1 name spit
1 name spita
1 name spital
1 name st
1 name t
1 name ta
1 name tal
1 name te
1 name tes
1 name test
1 name y
1 name a
这是我构建和执行搜索查询的方式:
QueryBuilder hospitalQb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Hospital.class).get();
Query hospitalQuery = hospitalQb.keyword().onFields("name")().matching(searchString).createQuery();
javax.persistence.Query persistenceQuery = fullTextEntityManager.createFullTextQuery(hospitalQuery, Hospital.class);
List<Hospital> results = persistenceQuery.getResultList();
问题是我的搜索查询也使用相同的ngram分析器。因此,当我寻找&#34;医院&#34;我会在名称中找到所有包含&#34; a&#34; -character的医院。 当我在其上调用toString方法时,这就是搜索查询的外观:
name:h name:ho name:hos name:hosp name:hospi name:hospit name:hospita name:hospital name:o name:os name:osp name:ospi name:ospit name:ospita name:ospital name:s name:sp name:spi name:spit name:spita name:spital name:p name:pi name:pit name:pita name:pital name:i name:it name:ita name:ital name:t name:ta name:tal name:a name:al name:l
所以问题是,是否有人知道更好的分析器配置或其他方式构建解决问题的搜索查询?
答案 0 :(得分:5)
您可以设置第二个分析器,除了它没有ngram过滤器之外,然后覆盖用于查询的分析器:
QueryBuilder hospitalQb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Hospital.class)
.overridesForField( "name", "my_analyzer_without_ngrams" )
.get();
// Then it's business as usual
此外,如果您要实施某种自动完成功能(foo*
),而不是单词搜索(*foo*
),则可能需要使用EdgeNGramFilterFactory
代替{ {1}}:它只会生成作为索引标记前缀的ngram。