Paged Search Results

Some searches may return large numbers of results. When there is no easy way to filter out a smaller amount, it would be convenient to have the server return only a certain number of results each time it is called. This is known as paged search results. Each "page" of the result could then be displayed at the time, with links to the next and previous page. Without this functionality, the client must either manually limit the search result into pages, or retrieve the whole result and then chop it into pages of suitable size. The former would be rather complicated, and the latter would be consuming unnecessary amounts of memory.

Some LDAP servers have support for the PagedResultsControl, which requests that the results of a search operation are returned by the LDAP server in pages of a specified size. The user controls the rate at which the pages are returned, simply by the rate at which the searches are called. However, the user must keep track of a cookie between the calls. The server uses this cookie to keep track of where it left off the previous time it was called with a paged results request.

Spring LDAP provides support for paged results by leveraging the concept for pre- and postprocessing of an LdapContext that was discussed in the previous sections. It does so by providing two classes: PagedResultsRequestControl and PagedResultsCookie. The PagedResultsRequestControl class creates a PagedResultsControl with the requested page size and adds it to the LdapContext. After the search, it gets the PagedResultsResponseControl and retrieves two pieces of information from it: the estimated total result size and a cookie. This cookie is a byte array containing information that the server needs the next time it is called with a PagedResultsControl. In order to make it easy to store this cookie between searches, Spring LDAP provides the wrapper class PagedResultsCookie.

Below is an example of how the paged search results functionality may be used:

Example 5.2. Paged results using PagedResultsRequestControl

public PagedResult getAllPersons(PagedResultsCookie cookie) {
   PagedResultsRequestControl control = new PagedResultsRequestControl(PAGE_SIZE, cookie);
   SearchControls searchControls = new SearchControls();
   searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
   
   List persons = ldapTemplate.search("", "objectclass=person", searchControls, control);
   
   return new PagedResult(persons, control.getCookie());
 }

In the first call to this method, null will be supplied as the cookie parameter. On subsequent calls the client will need to supply the cookie from the last search (returned wrapped in the PagedResult) each time the method is called. When the actual cookie is null (i.e. pagedResult.getCookie().getCookie() returns null), the last batch has been returned from the search.