Retrieving query results

After constructing a query, you can specify a number of retrieval options to further control the results it returns. See datastore queries for more information on structuring queries for your app.

  1. Iterating through query results
  2. Retrieving selected properties from an entity
  3. Setting a limit for your query
  4. What's next?

Retrieving a single entity

To retrieve just a single entity matching your query, use the method PreparedQuery.asSingleEntity():

Query q =
    new Query("Person")
        .setFilter(new FilterPredicate("lastName", FilterOperator.EQUAL, targetLastName));

PreparedQuery pq = datastore.prepare(q);
Entity result = pq.asSingleEntity();

This returns the first result found in the index that matches the query. (If there is more than one matching result, it throws a TooManyResultsException.)

Iterating through query results

When iterating through the results of a query using the PreparedQuery.asIterable() and PreparedQuery.asIterator() methods, Cloud Datastore retrieves the results in batches. By default each batch contains 20 results, but you can change this value using FetchOptions.chunkSize(). You can continue iterating through query results until all are returned or the request times out.

Retrieving selected properties from an entity

To retrieve only selected properties of an entity rather than the entire entity, use a projection query. This type of query runs faster and costs less than one that returns complete entities.

Similarly, a keys-only query saves time and resources by returning just the keys to the entities it matches, rather than the full entities themselves. To create this type of query, use the Query.setKeysOnly() method:

Query q = new Query("Person").setKeysOnly();

Setting a limit for your query

You can specify a limit for your query to control the maximum number of results returned in one batch. The following example retrieves the five tallest people from Cloud Datastore:

private List<Entity> getTallestPeople() {
  DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  Query q = new Query("Person").addSort("height", SortDirection.DESCENDING);

  PreparedQuery pq = datastore.prepare(q);
  return pq.asList(FetchOptions.Builder.withLimit(5));

What's next?