没有物理实体作为 parent 键是否有任何副作用

Is there any side effect of not having a physical entity for it to act as parent key

如果我阅读 google 应用引擎教程,我可以看到他们的示例似乎鼓励我们为实体提供 parent。

因此,我有以下可行的代码,用于创建用户(电子邮件是唯一的)

def parent_key():
    return ndb.Key('parent', 'parent')


class User(ndb.Model):
    email = ndb.StringProperty(required = True)
    timestamp = ndb.DateTimeProperty(required = True)


class RegisterHandler2(webapp2.RequestHandler):
    def get(self):
        email = self.request.get('email')
        user_timestamp = int(time.time())
        user = User.get_or_insert(email, parent=parent_key(), email=email, timestamp=datetime.datetime.fromtimestamp(user_timestamp))

请注意,parent实体实际上并不存在。

虽然上面的代码运行得很好,但我想知道如果 parent 实体在物理上不存在,是否会出现任何可能的问题?

我对没有 parent 的担忧之一是 最终的一致性 。写操作后,我希望我的读操作能够获取最新的写入值。我使用 User.get_or_insert 来写(和读),而 User.get_by_id 只读。

我想在执行 User.get_or_insert 后,下一个请求 User.get_by_id 将 return 最新值。我想知道,要实现 强一致性 ,parent key 是不是很重要?

  1. 只要您实际上不需要这个父实体就没有问题。

  2. 您不应该轻率地决定使用父实体。事实上,使用实体组(父子实体)限制了每秒可以更新的实体数量,并且需要知道父键才能检索子实体。

您可能 运行 陷入严重的问题。例如,如果实体 "User" 是某个父实体的子实体,那么所有其他实体都是实体 "User" 的子实体,这会将您的所有数据变成一个大实体组。假设您的应用相当活跃,您将看到由于此性能限制而导致的数据存储操作失败。

另请注意,如果您必须将父实体的密钥包含在其中,实体的密钥会变得更长。如果您创建一个实体链(例如父 -> 用户 -> 相册 -> 照片),每个 "photo" 实体的键将包括一个相册键、一个用户键和一个父实体键。它成为管理的噩梦,需要更多的存储空间 space.

使用与实际具有属性的实体不对应的父键(我认为您指的是 'physical entity')是一种标准技术。

您甚至可以稍后决定向该键添加属性。

多年来我一直在使用这种技术。