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
- Iterating through query results
- Retrieving selected properties from an entity
- Setting a limit for your query
- What's next?
Retrieving a single entity
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
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)
- Learn the common restrictions for queries on Cloud Datastore.
- Learn about query cursors, which allow an application to retrieve a query's results in convenient batches.
- Understand data consistency and how data consistency works with different types of queries on Cloud Datastore.
- Learn the basic syntax and structure of queries for Cloud Datastore.