Pagination

When a search query returns a huge number of search results, it is usually not desirable (or perhaps even possible) to present them to the user all at once. A common solution is pagination, or displaying search results one "page" at a time.

A Hibernate Search FullTextQuery object has methods for making pagination easy:

…
hibernateQuery.setFirstResult(10);
hibernateQuery.setMaxResults(5);
List<App> apps = hibernateQuery.list();
…

The setMaxResults method declares the maximum size of the page. On the last line of the preceding code snippet, the apps list will contain no more than five App objects, even if the query has thousands of matches.

Of course, pagination wouldn't be very useful if the code always grabbed the first five results. We also need the ability to grab the next page, and then the next page, and so on. So the setFirstResult method tells Hibernate Search where to start.

For example, the preceding code snippet starts with the eleventh result item (the parameter is 10, but results are a zero-indexed). The query is then set to grab the next five results. The next incoming request might therefore use hibernateQuery.setFirstResult(15).

The last piece of the puzzle is knowing how many results there are, so you can plan for the correct number of pages:

…
intresultSize = hibernateQuery.getResultSize();
…

The getResultSize method is more powerful than it appears at first glance, because it calculates the number using only Lucene indexes. A regular database query across all matching rows could be a very resource-intensive operation, but it is a relatively lightweight matter for Lucene.

Note

This chapter's version of the example applications now use pagination for search results, with a maximum of five results per page. Explore the SearchServlet and search.jsp results page to see how they use the result size and the current starting point to build the "previous" and "next" links as needed.

A look at the VAPORware Markeplace updates in action is as follows:

Pagination
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset