5.2.2. Result size

It is sometime useful to know the total number of matching documents:
  • for the Google-like feature 1-10 of about 888,000,000
  • to implement a fast pagination navigation
  • to implement a multi step search engine (adding approximation if the restricted query return no or not enough results)
Of course it would be too costly to retrieve all the matching documents. Hibernate Search allows you to retrieve the total number of matching documents regardless of the pagination parameters. Even more interesting, you can retrieve the number of matching elements without triggering a single object load.

Example 5.11. Determining the result size of a query

org.hibernate.search.FullTextQuery query = s.createFullTextQuery( luceneQuery, Book.class );
assert 3245 == query.getResultSize(); //return the number of matching books without loading a single one

org.hibernate.search.FullTextQuery query = s.createFullTextQuery( luceneQuery, Book.class );
query.setMaxResults(10);
List results = query.list();
assert 3245 == query.getResultSize(); //return the total number of matching books regardless of pagination

Note

Like Google, the number of results is approximative if the index is not fully up-to-date with the database (asynchronous cluster for example).