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?

Iterating through query results

When iterating through the results of a query using the Run method of a Query value, Cloud Datastore retrieves the results in batches. By default each batch contains 20 results. 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.

q := datastore.NewQuery("Person")
t := q.Run(ctx)
for {
	var p Person
	k, err := t.Next(&p)
	if err == datastore.Done {
		break // No further entities match the query.
	}
	if err != nil {
		log.Errorf(ctx, "fetching next Person: %v", err)
		break
	}
	// Do something with Person p and Key k
	doSomething(k, p)
}

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

q := datastore.NewQuery("Person")
var people []Person
keys, err := q.GetAll(ctx, &people)
if err != nil {
	log.Errorf(ctx, "fetching people: %v", err)
	return
}
for i, p := range people {
	k := keys[i]
	// Do something with Person p and Key k
	doSomething(k, p)
}

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

q := datastore.NewQuery("Person").KeysOnly()

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 := datastore.NewQuery("Person").Order("-Height").Limit(5)
var people []Person
_, err := q.GetAll(ctx, &people)
// check err

for _, p := range people {
	log.Infof(ctx, "%s %s, %d inches tall", p.FirstName, p.LastName, p.Height)
}

What's next?

Send feedback about...

App Engine standard environment for Go