Skip to content

retrieving query results

ludoch edited this page Apr 15, 2026 · 2 revisions

Retrieving query results

Not applicable to this runtime.

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.

Retrieving a single entity

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

View QueriesTest.java on GitHub (region: single_retrieval_example)

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 Run method of a Query value

PreparedQuery.asIterable() and PreparedQuery.asIterator() methods, 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.

To iterate over each entity that matches your query, use the Run method to obtain an Iterator, with which you can step through each entity using the Iterator's Next method.

To retrieve all entities matching your query at once, use the GetAll method.

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, call the KeysOnly method when constructing the Query. use the Query.setKeysOnly() method:

View QueriesTest.java on GitHub (region: keys_only_example)

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 Datastore:

View QueriesTest.java on GitHub (region: query_limit_example)

What's next?

We recommend using the NDB Client Library for Datastore, which has several benefits compared to this client library, such as automatic entity caching via the Memcache API. If you are currently using the older DB Client Library, see the DB to NDB Migration Guide.

Clone this wiki locally