Hibernate-Search通配符搜索未返回预期结果

时间:2016-10-04 18:41:21

标签: java lucene hibernate-search

我正在尝试查询以下索引的POJO:

@Entity
@Indexed
@AnalyzerDef(name="userAnalyzer",
             tokenizer = @TokenizerDef(factory=StandardTokenizerFactory.class),
             filters = {
                 @TokenFilterDef(factory=LowerCaseFilterFactory.class),
                 @TokenFilterDef(factory=SnowballPorterFilterFactory.class, params = {
                                      @Parameter(name="language", value="English"
                 })
             }
)
public class User {
   @Id
   private long id;

   @IndexEmbedded
   private List<Address> addresses;   // Address.street is what I am looking for

   @Field
   private String firstName;

   @Field
   private String lastName;

   private List<AKA> akas;

   private List<Wife> wives;

   ...

}

基本上我正在尝试在Hibernate-search(Lucene)中执行以下SQL:

select u.* 
from User 
where u.firstName like ':fname%'
and u.lastName like ':lname%'

以下是我的工作并不一致:

   ...
   if(Objects.nonNull(u.getFirstName()){  
       luceneBoolQuery.must(queryBuilder.keyword().wildcard().onField("firstName").matching(u.getFirstName().toLowerCase()).createQuery());
    }
    if(Objects.nonNull(u.getLastName()){
      luceneBoolQuery.must(queryBuilder.keyword().wildcard().onField("lastName").matching(u.getLastName().toLowerCase()).createQuery());
    }
    Query luceneQuery = luceneBoolQuery.createQuery();

    Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, User.class);
    ...
    ...

有人可以帮我制作这个查询来拉回上面的SQL会返回的内容吗?

1 个答案:

答案 0 :(得分:0)

您的查询不包含字符串通配符(&#39; *&#39;)。也许这会按你的意愿运作?

...
if(Objects.nonNull(u.getFirstName()){  
   luceneBoolQuery.must(queryBuilder.keyword().wildcard().onField("firstName").matching(u.getFirstName().toLowerCase() + "*").createQuery());
}
if(Objects.nonNull(u.getLastName()){
  luceneBoolQuery.must(queryBuilder.keyword().wildcard().onField("lastName").matching(u.getLastName().toLowerCase() + "*").createQuery());
}
Query luceneQuery = luceneBoolQuery.createQuery();

Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, User.class);
...
...

此外,您的分析器仅定义,不归因于您的字段,因此您的搜索仍然区分大小写。

您需要添加@Analyzer注释:

@Field
@Analyzer(definition = "userAnalyzer")
private String firstName;

@Field
@Analyzer(definition = "userAnalyzer")
private String lastName;

或者,您可以在整个班级中添加注释:

@Entity
@Indexed
@AnalyzerDef(name="userAnalyzer",
             tokenizer = @TokenizerDef(factory=StandardTokenizerFactory.class),
             filters = {
                 @TokenFilterDef(factory=LowerCaseFilterFactory.class),
                 @TokenFilterDef(factory=SnowballPorterFilterFactory.class, params = {
                                      @Parameter(name="language", value="English"
                 })
             }
)
@Analyzer(definition="userAnalyzer") // Difference HERE
public class User {
...

...当然,在测试之前,您必须重新编制数据索引。

有关使用分析仪的更多信息,请参阅参考文档:https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#_analyzer