ndb 在没有父级的情况下通过 ID 检索实体键 [英] ndb retrieving entity key by ID without parent

查看:28
本文介绍了ndb 在没有父级的情况下通过 ID 检索实体键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个知道实体 ID 和祖先的实体键.ID 在祖先定义的实体组中是唯一的.在我看来,使用 ndb 接口是不可能的.据我了解数据存储可能是由于此操作需要执行完整索引扫描这一事实造成的.我使用的解决方法是在模型中创建一个计算属性,该属性将包含密钥的 id 部分.我现在可以进行祖先查询并获取密钥

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?

更新似乎对于数据存储,自然的解决方案是使用完整路径而不是标识符.一开始我觉得这太麻烦了.在阅读了 Dragonx 的回答后,我重新设计了我的应用程序.令我惊讶的是,现在一切看起来都简单多了.其他好处是我的实体将使用更少的空间,我不需要额外的索引.

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.

推荐答案

我也遇到了这个问题.我认为您确实有解决方案.

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

更好的解决方案是停止使用 ID 来引用实体,并存储实际密钥或完整路径.

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

在内部,我使用密钥而不是 ID.

Internally, I use keys instead of IDs.

在我的 rest API 上,我曾经使用 http://url/kind/id(其中 id 看起来像123")来获取实体.我修改了它以提供实体的完整祖先路径:http://url/kind/ancestor-ancestor-id (789-456-123),然后我会解析该字符串,生成一个钥匙,然后通过钥匙获得.

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.

这篇关于ndb 在没有父级的情况下通过 ID 检索实体键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆