ndb retrieving entity key by ID without parent

2019-04-07 08:34发布

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.

4条回答
Deceive 欺骗
2楼-- · 2019-04-07 09:05

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()
查看更多
我命由我不由天
3楼-- · 2019-04-07 09:08

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
查看更多
干净又极端
4楼-- · 2019-04-07 09:17

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.

查看更多
别忘想泡老子
5楼-- · 2019-04-07 09:32

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.

查看更多
登录 后发表回答