Querying in Google Cloud Datastore
So far, we have only been putting and getting single objects into and out of Google Cloud Datastore. When we display a list of answers to a question, we want to load all of these answers in a single operation, which we can do with datastore.Query.
The querying interface is a fluent API, where each method returns the same object or a modified object, allowing you to chain calls together. You can use it to build up a query consisting of ordering, limits, ancestors, filters, and so on. We will use it to write a function that will load all the answers for a given question, showing the most popular (those with a higher Score value) first.
Add the following function to answers.go:
func GetAnswers(ctx context.Context, questionKey *datastore.Key)
([]*Answer, error) {
var answers []*Answer
answerKeys, err := datastore.NewQuery("Answer").
Ancestor(questionKey).
Order("-Score").
Order("-CTime").
GetAll(ctx, &answers)
for i, answer ...