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 Query.get() (or GqlQuery.get()):

q = Person.all()
q.filter("last_name =", target_last_name)

result = q.get()

This returns the first result found in the index that matches the query.

Iterating through query results

When iterating through the results of a query using the run() method of a Query or GqlQuery object, Cloud Datastore retrieves the results in batches. By default each batch contains 20 results, but you can change this value using the method's batch_size parameter. 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, set keys_only=True when constructing the query object:

q = Person.all(keys_only=True)

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:

q = Person.all()
q.order("-height")

for p in q.run(limit=5):
  print "%s %s, %d inches tall" % (p.first_name, p.last_name, p.height)

What's next?