google 如果我使用祖先关系创建密钥,应用引擎数据存储获取失败

google app engine datastore get fails if I create the key using ancestor relationship

当我将消息插入数据存储区时,我使用消息的序列号创建了一个键,并与发送消息的用户建立了祖先关系。当我尝试使用仅从序列号创建的密钥检索消息时,它失败了。如果我将插入更改为使用仅基于序列号的密钥,则稍后的检索会成功。

代码方面

失败:

存储空间:

p_key = ndb.Key(StoredBcastMsg,sendingUser)
c_key = ndb.Key(StoredBcastMsg,prof['seqNum'],parent=p_key)
prof['key']=c_key
StoredBcastMsg(**prof).put()

检索失败

msgToRet=ndb.Key(StoredBcastMsg,seqNum).get() #Fails even though sequence number is there in the store

这成功了:

存储空间:

prof['key']=c_key
StoredBcastMsg(**prof).put()
c_key = ndb.Key(StoredBcastMsg,prof['seqNum'])

检索成功:

msgToRet=ndb.Key(StoredBcastMsg,seqNum).get() #Succeeds

这是预期的行为吗?我认为在创建密钥时添加 parent= 标签的唯一区别是创建一个祖先关系,该关系允许有效地回答诸如“给我用户 X 发送的所有消息”之类的查询。

父键是子键的一部分,您需要完整的键才能检索实体。

因此,要检索子实体,您需要知道完整密钥,这意味着您需要知道父密钥。

注意:通过键的父子关系不会创建普通 SQL 数据库所具有的关系。它只是将父项和子项放在同一个 "entity group"(将实体放在同一台服务器上的花哨词),这允许您在它们上进行交易。

正如你上面所说:

p_key = ndb.Key(StoredBcastMsg,sendingUser)
c_key = ndb.Key(StoredBcastMsg,prof['seqNum'],parent=p_key)
prof['key']=c_key
StoredBcastMsg(**prof).put()

这成功了。要检索此实体,您必须使用完全相同的密钥:

msgToRet=c_key.get()

或者,在更长的格式中:

p_key = ndb.Key(StoredBcastMsg,sendingUser)
msgToRet=ndb.Key(StoredBcastMsg,seqNum,parent=p_key).get()