我刚刚开始使用Hibernate Search。我用来进行搜索的代码来自参考指南:
FullTextEntityManager fullTextEntityManager =
Search.getFullTextEntityManager(em);
EntityTransaction transaction = em.getTransaction();
try
{
transaction.begin();
// create native Lucene query using the query DSL
// alternatively you can write the Lucene query using the
// Lucene query parser or the Lucene programmatic API.
// The Hibernate Search DSL is recommended though
SearchFactory sf = fullTextEntityManager.getSearchFactory();
QueryBuilder qb = sf
.buildQueryBuilder().forEntity(Item.class).get();
org.apache.lucene.search.Query query = qb
.keyword()
.onFields("title", "description")
.matching(queryString)
.createQuery();
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, Item.class);
// execute search
@SuppressWarnings("unchecked")
List<Item> result = persistenceQuery.getResultList();
transaction.commit();
return result;
}
catch (RuntimeException e)
{
transaction.rollback();
throw e;
}
我注意到查询术语被解释为析取(OR)中的术语。我希望将它们解释为连词术语。
答案 0 :(得分:3)
如果您使用Query解析器,那么您可以这样做:
QueryParser queryParser = new QueryParser("all", new GermanSnowBallAnalyzer());
queryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
Query luceneQuery = queryParser.parse(QueryParser.escape(keyword));
答案 1 :(得分:2)
由于您使用的是Hibernate Search查询DSL,因此您可以将查询编写为:
Query luceneQuery = qb
.bool()
.must( qb.keyword().onField("title").matching(queryString).createQuery() )
.must( qb.keyword().onField("description").matching(queryString).createQuery() )
.createQuery();
请注意,查询字符串不会通过Lucene查询解析器进行解析。它必须包含您想要搜索它们的术语(将应用分析器!)
答案 2 :(得分:1)
我不太了解Hibernate Search,但我猜'keyword()'会基于标签准备搜索,这些标签通常是基于OR的。
上面的两个链接中有类似的问题,希望它有所帮助: Keyword (OR, AND) search in Lucene https://forum.hibernate.org/viewtopic.php?f=9&t=1008903&start=0