Hibernate:5.2.8.Final
Hibernate搜索:5.7.0.Final
配置:
FullTextEntityManager ftsEntityManager = Search.getFullTextEntityManager(entityManager);
QueryBuilder queryBuilder = ftsEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity(Report.class).get();
BooleanQuery.Builder builder = new BooleanQuery.Builder();
BooleanQuery.Builder cmpBuilder = new BooleanQuery.Builder();
companies.forEach(cmp -> cmpBuilder.add(
NumericRangeQuery.newLongRange("merchant.company.company_id", cmp.getId(), cmp.getId(), true, true),
BooleanClause.Occur.SHOULD));
builder.add(cmpBuilder.build(), BooleanClause.Occur.MUST);
builder.add(new TermQuery(new Term("status", status.name())), BooleanClause.Occur.MUST);
org.apache.lucene.search.Query fromQuery = queryBuilder.range()
.onField("createdAt")
.above(from)
.createQuery();
org.apache.lucene.search.Query toQuery = queryBuilder.range()
.onField("createdAt")
.below(to)
.createQuery();
builder.add(fromQuery, BooleanClause.Occur.MUST);
builder.add(toQuery, BooleanClause.Occur.MUST);
FullTextQuery fullTextQuery = ftsEntityManager.createFullTextQuery(builder.build(), Report.class);
int results = fullTextQuery.getResultSize();
EntityGraph graph = this.entityManager.getEntityGraph("Report.fetchMerchantAndAccount");
List resultList = fullTextQuery
.setFirstResult(pageable.getOffset())
.setMaxResults(pageable.getPageSize())
.setHint("javax.persistence.fetchgraph", graph)
.getResultList();
我的代码:
2017-03-24 02:39:50.942 DEBUG 1984 --- [tp1560534902-96] org.hibernate.search.fulltext_query : HSEARCH000274: Executing Lucene query '+(merchant.company.company_id:[2 TO 2]) +status:COMPLETE +createdAt:[0000020161102000000000000000 TO *] +createdAt:[* TO 0000020170324235959999999999]'
记录查询:
+(merchant.company.company_id:[2 TO 2]) +status:COMPLETE
答案 0 :(得分:0)
问题是我应该使用QueryBuilder而不是Lucene类。 所以,改变这个:
companies.forEach(cmp -> cmpBuilder.add(
NumericRangeQuery.newLongRange("merchant.company.company_id", cmp.getId(), cmp.getId(), true, true),
BooleanClause.Occur.SHOULD));
到此:
companies.forEach(cmp -> cmpBuilder.add(queryBuilder.range().onField("merchant.company.company_id")
.from(cmp.getId()).to(cmp.getId()).createQuery(), BooleanClause.Occur.SHOULD));
和此:
builder.add(new TermQuery(new Term("status", status.name())), BooleanClause.Occur.MUST);
到此:
builder.add(queryBuilder.keyword().onField("status").matching(status).createQuery(), BooleanClause.Occur.MUST);
解决了问题!