5.5. Querying

5.5. Querying

The second most important capability of Hibernate Search™ is the ability to execute a Lucene query and retrieve entities managed by an Hibernate session, providing the power of Lucene without living the Hibernate paradygm, and giving another dimension to the Hibernate classic search mechanisms (HQL, Criteria query, native SQL query).

To access the Hibernate Search™ querying facilities, you have to use an Hibernate FullTextSession. A SearchSession wrap an regular org.hibernate.Session to provide query and indexing capabilities.

Session session = sessionFactory.openSession();
...
FullTextSession fullTextSession = Search.createFullTextSession(session);

The search facility is built on native Lucene queries.

org.apache.lucene.QueryParser parser = new QueryParser("title", new StopAnalyzer() );

org.hibernate.lucene.search.Query luceneQuery = parser.parse( "summary:Festina Or brand:Seiko" );
	org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery( luceneQuery );

List result = fullTextQuery.list(); //return a list of managed objects

The Hibernate query built on top of the Lucene query is a regular org.hibernate.Query, you are is the same paradygm as the other Hibernate query facilities (HQL, Native or Criteria). The regular list(), uniqueResult(), iterate() and scroll() can be used.

If you expect a reasonnable result number and expect to work on all of them, list() or uniqueResult() are recommanded. list() work best if the entity batch-size is set up properly. Note that Hibernate Seach has to process all Lucene Hits elements when using list(), uniqueResult() and iterate(). If you wish to minimize Lucene document loading, scroll() is more appropriate, Don't forget to close the ScrollableResults object when you're done, since it keeps Lucene resources.

An efficient way to work with queries is to use pagination. The pagination API is exactly the one available in org.hibernate.Query:

org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery( luceneQuery );
fullTextQuery.setFirstResult(30);
fullTextQuery.setMaxResult(20);
fullTextQuery.list(); //will return a list of 20 elements starting from the 30th

Only the relevant Lucene Documents are accessed.