Hibernate search beginner question
-
26-09-2019 - |
Question
I am just beginning with Hibernate Search. The code I am using to do the search is taken from the reference guide:
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;
}
I notice that the query terms are interpreted as terms in a disjunction(OR). I would like them to be interpreted as conjunction terms instead.
Solution
If you use the Query parser, then you could do it this way:
QueryParser queryParser = new QueryParser("all", new GermanSnowBallAnalyzer());
queryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
Query luceneQuery = queryParser.parse(QueryParser.escape(keyword));
OTHER TIPS
Since you are using the Hibernate Search query DSL you could write your query as:
Query luceneQuery = qb
.bool()
.must( qb.keyword().onField("title").matching(queryString).createQuery() )
.must( qb.keyword().onField("description").matching(queryString).createQuery() )
.createQuery();
Note that the query string is not parsed via the Lucene query parser. It has to contain the terms as you want to search for them (analyzers will be applied!)
I don't know Hibernate Search too much, but I guess 'keyword()' will prepare a search based on tags, that are generally OR-based.
There are similar questions in the two links above, hope it helps: Keyword (OR, AND) search in Lucene https://forum.hibernate.org/viewtopic.php?f=9&t=1008903&start=0