Paginated results
The Query API includes methods for returning paginated results. A paginated result prevents all query results from being returned at one time, potentially exceeding system memory. It allows you to incrementally return and process query results in batches.
In the following snippet, a PaginatedResult object is returned that is limited to the first 10 User objects.
1①PaginatedResult<User> results = Query.from(User.class)2.select(0, 10);3②List<User> users = results.getItems();
- ①Returns a
PaginatedResultwith select(long offset, int limit). This method specifies the number of objects to return starting at a particular offset. If the offset were set to 5 and the limit set to 15, the method would return 15 instances starting at offset 5. - ②Returns the objects contained by
PaginatedResult.
The PaginatedResult object only contains the number of objects specified in select(long offset, int limit), which is typically a subset of the total objects retrieved. For example, a query might return a total of 1,000 objects, which can be determined with the getCount method on PaginatedResult.
To iterate query results in batches, use the PaginatedResult methods hasNext() and getNextOffset(). The following snippet builds paginated results in batches of 100 objects.
1①int limit = 100;2②Query<User> query = Query.from(User.class);3③PaginatedResult<User> result = query.select(0, limit);4④while (result.hasNext()) {5/* Do something with the current batch of items referenced in the result object */6result = query.select(result.getNextOffset(), limit);7}
- ①Variable for limiting the number of retrieved records in a page.
- ②Instantiates a
Queryobject for searching users. - ③Returns a
PaginatedResultwith the first 100Userobjects. - ④Iterates
PaginatedResultin batches of 100 items. Successive iterations continue until all of the objects retrieved by the query are processed.