Hibernate Search - SearchQuery Example

Query object

The example presented in most of this documentation fetch the query results directly at the end of the query definition DSL, not showing any "query" object that can be manipulated. This is because the query object generally only makes code more verbose without bringing anything worthwhile.

However, in some cases a query object can be useful. To get a query object, just call toQuery() at the end of the query definition:

Getting a SearchQuery object

SearchQuery<Book> query = searchSession.search( Book.class ) 
        .where( f -> f.matchAll() )
        .toQuery(); 
List<Book> hits = query.fetchHits( 20 ); 
Build the query as usual.
Retrieve a SearchQuery object.


Fetch the results.
This query object supports all fetch* methods supported by the query DSL. The main advantage over calling these methods directly at the end of a query definition is mostly related to debugging (see Debugging a query), but the query object can also be useful if you need an adapter to another API.

Hibernate Search provides an adapter to JPA and Hibernate ORM’s native APIs, i.e. a way to turn a SearchQuery into a javax.persistence.TypedQuery (JPA) or a org.hibernate.query.Query (native ORM API):

Getting a SearchQuery object

SearchQuery<Book> query = searchSession.search( Book.class ) 
        .where( f -> f.matchAll() )
        .toQuery(); 
javax.persistence.TypedQuery<Book> jpaQuery = Search.toJpaQuery( query ); 
org.hibernate.query.Query<Book> ormQuery = Search.toOrmQuery( query ); 


Build the query as usual.
Retrieve a SearchQuery object.
Turn the SearchQuery object into a JPA query.
Turn the SearchQuery object into a Hibernate ORM query.
The resulting query does not support all operations, so is recommended to only convert search queries when absolutely required, for example when integrating with code that only works with Hibernate ORM queries.

The following operations are expected to work correctly in most cases, even though they may behave slightly differently from what is expected from a JPA TypedQuery or Hibernate ORM Query in some cases (including, but not limited to, the type of thrown exceptions):

Hit retrieval methods (list, getResultList, uniqueResult, …​ ).

setFirstResult/setMaxResults and getters.

setFetchSize

unwrap

The following operations are known not to work correctly, with no plan to fix them at the moment:

Hints (setHint, …​).

Parameter-related methods (setParameter, …​).

Result transformer (setResultTransformer, …​); use composite projections instead.

Lock-related methods (setLockOptions, …​).

And more (this list is not exhaustive).

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations