Question

I'm trying to get entity Key by its int Id. (not the entity itself, but it's Key) (in the long run I do it to find entities parent)

Data from DatastoreViewer:

Entity Kind
File
Entity Key
ag9kZXZ-dHJhc2hib3hhcHByIgsSBEZpbGUYgICAgICAwAoMCxIERmlsZRiAgICAgIDACww
ID
6473924464345088
Parent
ag9kZXZ-dHJhc2hib3hhcHByEQsSBEZpbGUYgICAgICAwAoM
File: id=5910974510923776

I do it like this:

k := datastore.NewKey(c, "File", "", 6473924464345088, nil)
currentDirQuery := datastore.NewQuery("File").Filter("__key__ =", k).KeysOnly()
keys, err := currentDirQuery.GetAll(c, nil)

The length if keys is 0. What do I do wrong?

Was it helpful?

Solution

If you have the key already why are doing a keys only query matching the key ? Why don't you just do a datastore.Get() with the key?

As to why your keys_only query is not working, you are not including the ancestor in the key you are constructing , the key in your example has a parent you showed ag9kZXZ-dHJhc2hib3hhcHByEQsSBEZpbGUYgICAgICAwAoM this urlsafe version of the key must have a parent if you are specifying an ancestor.

Using python we can decode this key

> ndb.Key(urlsafe="ag9kZXZ-dHJhc2hib3hhcHByIgsSBEZpbGUYgICAgICAwAoMCxIERmlsZRiAgICAgIDACww")
Key('File', 5910974510923776, 'File', 6473924464345088, app='dev~trashboxapp')

See the parent Key is Key('File', 5910974510923776)

You can not perform a partial match on a child with the key you created for the query. You can only perform ancestor queries which will return the ancestor and all of it's children irrespective of the depth of the heirarchy.

This also means a datastore.Get() will fail with the key you have created in your example code.

So construct you key so that it includes the ancestor - see the docs https://developers.google.com/appengine/docs/go/datastore/entities#Go_Retrieving_an_entity

But to be honest what you are doing is completely redundant unless it's just an excercise in understanding whats going on and your trying to roundtrip a key -> query -> key

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top