Join hibernate search query with criteria query restriction

Code Junkie picture Code Junkie · Oct 11, 2013 · Viewed 8.5k times · Source

I'm wondering how you would join the following two queries together.

A standard criteria query

Criteria result1 = session.createCriteria(Store.class).add(Restrictions.eq("department.name", category));

and a FullTextSearch

    QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Store.class).get();
    Query luceneQuery = queryBuilder.keyword().onFields("productTitle").matching(keyword).createQuery();

    // wrap Lucene query in a javax.persistence.Query
    org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, Store.class);
    fullTextQuery.setMaxResults(15);
    fullTextQuery.setFirstResult(0);

I pass in additional parameters through the URL plus a keyword parameter, I do not want to fully rely on keyword search. Does anybody know how to make these work together?

Thanks.

Answer

Hardy picture Hardy · Oct 11, 2013

The Hibernate Search documentation actually discourages using Criteria queries combined with full text search queries (except for specifying the fetch type).

Only fetch mode can be adjusted, refrain from applying any other restriction. While it is known to work as of Hibernate Search 4, using restriction (ie a where clause) on your Criteria query should be avoided when possible. getResultSize() will throw a SearchException if used in conjunction with a Criteria with restriction.

See also http://docs.jboss.org/hibernate/search/4.4/reference/en-US/html_single/index.html#d0e5722