Querying The Datastore In Golang

Here’s a demonstration of how to query the datastore in Go.

In this example we filter on PropertyOne, requiring it to be equal to true. You can also set other inequalities such as greater than ( > ). Kind is the kind of the entities to query, and PropertyTwodemonstrates ordering by descending order. CustomStruct is the struct that was used to create the entity. Remember to put your entity processing code just before the last brace ( } ).

//Search the datastore for entities
q := datastore.NewQuery(kind).Filter("PropertyOne =", true).Order("-PropertyTwo")
//Loop through each returned entity.
for t := q.Run(c); ; {
    //This represents the entity currently being processed.
    var x CustomStruct
    key, err := t.Next(&x)
    if err == datastore.Done {
        //This "error" means that we're done going through entities
        //Since we're done, break out of this loop.
        break
    }
    if err != nil {
        //Some other error happened. Report error and panic.
        c.Infof("Error in querying datastore: %v", err)
        panic(err)
    }
    //DO SOMETHING HERE WITH ENTITY x
}//end for going through q.Run