Java 8 has reached end of support and will be deprecated on January 31, 2026. After deprecation, you won't be able to deploy Java 8 applications, even if your organization previously used an organization policy to re-enable deployments of legacy runtimes. Your existing Java 8 applications will continue to run and receive traffic after their deprecation date. We recommend that you migrate to the latest supported version of Java.

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.

Retrieving a single entity

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

Queryq=
newQuery("Person")
.setFilter(newFilterPredicate("lastName",FilterOperator.EQUAL,targetLastName));
PreparedQuerypq=datastore.prepare(q);
Entityresult=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:

Queryq=newQuery("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:

privateList<Entity>getTallestPeople(){
DatastoreServicedatastore=DatastoreServiceFactory.getDatastoreService();
Queryq=newQuery("Person").addSort("height",SortDirection.DESCENDING);
PreparedQuerypq=datastore.prepare(q);
returnpq.asList(FetchOptions.Builder.withLimit(5));
}

What's next?

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025年12月09日 UTC.