Is it possible to get the ancestor key for a query result? Based on the datastore documentation (https://cloud.google.com/appengine/docs/go/datastore/reference#Query.Run) the query.Run() result only has a Cursor() and a Next() function and neither will lead you to an ancestor. It seems like this should be information that's in scope, unless the mechanics of Datastore prevent it. Is it up to the developer to write the ancestor into a property (with a matching kind) on the child (if we're willing to incur the cost) for it?
1 Answers
2
votes
If your query returns results, the ancestor is contained in the entity Key
.
The entity key is returned by Iterator.Next()
for example:
func (t *Iterator) Next(dst interface{}) (*Key, error)
From the key, use the Key.Parent()
method to get the ancestor.
See this example:
query := datastore.NewQuery("MyEntity")
e := MyEntity{}
for i := query.Run(ctx); ; {
if k, err = t.Next(&te); err == nil {
log.Infof("Ancestor / parent key: %v", k.Parent())
}
}
Note that the ancestor is stored in the datastore.Query
, but it is not exported:
type Query struct {
ancestor *Key
// ...
}
And the datastore.Iterator
returned by Query.Run()
contains the Query
, but it is also unexported:
type Iterator struct {
// q is the original query which yielded this iterator.
q *Query
//...
}
So you can't access these struct fields, your best bet is an actual entity in the result (or rather its key).