如何查询具有未知祖先的键的实体?

huangapple go评论89阅读模式
英文:

How to query for entity with key whose ancestor is not known?

问题

AB的祖先

type A struct {}
type B struct {}

无论祖先是否存在,我应该如何搜索stringIDstringIDB?(B和祖先A甚至可能不存在)

ctx := appengine.NewContext(r)
a := ??? // 'A'可能不存在,那我在这里该怎么办?
k := datastore.NewKey(ctx, "B", "stringID", 0, a)
e := new(B)
if err := datastore.Get(ctx, k, e); err != nil {
    http.Error(w, err.Error(), 500)
    return
}
英文:

A is ancestor of B

type A struct {}
type B struct {}

How would I search for B whose string ID is stringID, regardless of ancestor? (B and ancestor A may not even exist)

ctx := appengine.NewContext(r)
a := ??? // 'A' may not exist, so what do I do here?
k := datastore.NewKey(ctx, "B", "stringID", 0, a)
e := new(B)
if err := datastore.Get(ctx, k, e); err != nil {
    http.Error(w, err.Error(), 500)
    return
}

答案1

得分: 2

祖先实体可能不存在,但其ID或名称必须已知。否则,您将无法为子实体创建唯一键。请注意,A的子实体和B的子实体可能具有相同的ID或名称。

还要注意,您可以删除一个实体并创建一个新实体,但是一旦实体创建后,您无法更改其父实体。

英文:

Ancestor entity may not exist, but its ID or Name must be known. Otherwise you will not be able to create a unique key for a child entity. Note that child of A and child of B may have the same ID or Name.

Also note that you may delete one entity and create a new one, but you cannot change the parent of an entity once it's created.

答案2

得分: 1

你可以在不实际创建实体a的情况下为a创建一个键(只有在调用datastore.Put()时才会创建实体)。然后,你可以使用该键来创建b(或者只是它的键,如果你希望如此)。

至于查询方面:你可以对所有B类型的实体进行一个仅返回键的查询,然后对每个键检查键的字符串ID是否与你所需的stringID匹配。你可以获得多个结果-对于具有不同祖先的实体,字符串ID仅在相同的祖先(或根本没有祖先)下是唯一的。

英文:

You can create a key for a without actually creating the a entity (the entity is only created when you call datastore.Put()). You can then use that key to create b (or just its key, if so you desire).

As for the query aspect: you could do a keys-only query for all entities of B type, then for each key check if the key's stringID matches your desired stringID. You can get multiple results - for entities with different ancestors - stringID is unique only for the same ancestor (or no ancestor at all).

huangapple
  • 本文由 发表于 2016年8月22日 14:34:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/39072675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定