ndb retrieving entity key by ID without parent

江枫思渺然 提交于 2020-01-01 09:40:09

问题


I want to get an entity key knowing entity ID and an ancestor. ID is unique within entity group defined by the ancestor. It seems to me that it's not possible using ndb interface. As I understand datastore it may be caused by the fact that this operation requires full index scan to perform. The workaround I used is to create a computed property in the model, which will contain the id part of the key. I'm able now to do an ancestor query and get the key

class SomeModel(ndb.Model):
    ID = ndb.ComputedProperty( lambda self: self.key.id() )

    @classmethod
    def id_to_key(cls, identifier, ancestor):
        return cls.query(cls.ID == identifier,
                         ancestor = ancestor.key ).get( keys_only = True)

It seems to work, but are there any better solutions to this problem?

Update It seems that for datastore the natural solution is to use full paths instead of identifiers. Initially I thought it'd be too burdensome. After reading dragonx answer I redesigned my application. To my suprise everything looks much simpler now. Additional benefits are that my entities will use less space and I won't need additional indexes.


回答1:


I ran into this problem too. I think you do have the solution.

The better solution would be to stop using IDs to reference entities, and store either the actual key or a full path.

Internally, I use keys instead of IDs.

On my rest API, I used to do http://url/kind/id (where id looked like "123") to fetch an entity. I modified that to provide the complete ancestor path to the entity: http://url/kind/ancestor-ancestor-id (789-456-123), I'd then parse that string, generate a key, and then get by key.




回答2:


Since you have full information about your ancestor and you know your id, you could directly create your key and get the entity, as follows:

my_key = ndb.Key(Ancestor, ancestor.key.id(), SomeModel, id)
entity = my_key.get()

This way you avoid making a query that costs more than a get operation both in terms of money and speed.

Hope this helps.




回答3:


I want to make a little addition to dargonx's answer.

In my application on front-end I use string representation of keys:

str(instance.key())

When I need to make some changes with instence even if it is a descendant I use only string representation of its key. For example I have key_str -- argument from request to delete instance':

instance = Kind.get(key_str)
instance.delete()



回答4:


My solution is using urlsafe to get item without worry about parent id:

pk = ndb.Key(Product, 1234)
usafe = LocationItem.get_by_id(5678, parent=pk).key.urlsafe()
# now can get by urlsafe
item = ndb.Key(urlsafe=usafe)
print item


来源:https://stackoverflow.com/questions/12954899/ndb-retrieving-entity-key-by-id-without-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!