Reputation: 12895
I am using the following code for search using hibernate-search. But this tokenizes the search query and does an OR search, whereas I want to do an AND search. How do I do that?
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
String searchQuery = "test query";
QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Customer.class).get();
TermMatchingContext onFields = qb.keyword().onFields("customer.name","customer.shortDescription","customer.longDescription");
org.apache.lucene.search.Query query = onFields.matching(searchQuery).createQuery();
FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Customer.class);
List<Customization> result = persistenceQuery.getResultList();
Upvotes: 2
Views: 3078
Reputation: 19109
The OR logic is the default for Lucene. You can use a boolean DSL query as described here - http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-query-querydsl, however, that might not solve your problem yet, because you seem to have both query terms in a single string. Depending on your usecase (if for example the search string is provided by the user) it might be better to get the Lucene query from the Lucene query parser.
Upvotes: 3
Reputation: 12895
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Customer.class).get();
TermMatchingContext onFields = qb.keyword().onFields("customer.shortDescription", "customer.longDescription");
BooleanJunction<BooleanJunction> bool = qb.bool();
org.apache.lucene.search.Query query = null;
String[] searchTerms = searchQuery.split("\\s+");
for (int j = 0; j < searchTerms.length; j++) {
String currentTerm = searchTerms[j];
bool.must(onFields.matching(currentTerm).createQuery());
}
query = bool.createQuery();
FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Customer.class);
resultList = persistenceQuery.getResultList();
Upvotes: 3