I'm building a catalog application in Google App Engine, using Go, and Google Datastore. I'm using the Ancestor
features of the datatore to manage different product categories. Here's an example of some data:
Musical Instruments -> Guitars -> Gibson -> Les Paul
Musical Instruments -> Guitars -> Fender -> Stratocaster
Musical Instruments -> Bass Guitars -> Music Man -> Stingray
Musical Instruments is the root entity. When I click it, I expect to see Guitars
and Bass Guitars
, but instead I see everything that is a descendant of Musical Instruments
all the way to the last entity. Which is not what I'm looking for. I'm only interested in the direct descendants of Musical instruments at this point.
Some posts, like this one, suggest creating a field in the datastore to track direct parents. But, if I'm going to track parent entities manually, why use the Ancestor
features at all? Would it be faster than filtering queries who match a direct parent field?
Here's the method for getting categories:
func (cat *Category) GetCategories(r *http.Request, pk string) ([]CategoryReturn, error) {
//get context
c := appengine.NewContext(r)
var q *datastore.Query
var err error
//get parent key
k, err := datastore.DecodeKey(pk)
if err != nil {
//handle error
return []CategoryReturn{}, err
}
q = datastore.NewQuery("Category").Ancestor(k)
//populate category slices
var categories []CategoryReturn
keys, err := q.GetAll(c, &categories)
if err != nil {
//handle error
return []CategoryReturn{}, err
}
//create return object
results := make([]CategoryReturn, 0, 20)
for i, r := range categories {
k := keys[i]
y := CategoryReturn {
Name: r.Name,
Id: k.IntID(),
Key: k.Encode(),
}
results = append(results, y)
}
return results, nil
}