How can I query for direct descendants only?

眉间皱痕 提交于 2019-12-10 13:25:27

问题


Let's say I have entities a, b and c all of the same type, and the situation is like this:

entity a is parent for entity b entity b is parent for entity c

Now if I do the following query

query = ndb.Query(ancestor=a.key)
result = query.fetch()

The result will contain both b and c entities. Is there a way I can filter out c so that only entities that are direct descendants remain? Any way apart from me going through the results and removing them I mean.


回答1:


The only way to do this is to modify your schema, adding a 'parent' KeyProperty that references an entity's direct parent, then filtering on that.




回答2:


Actually, this is not supported at all. Nick's answer does work but only if you can specify the entity kind in your query which the OP did not specify:

"Kindless queries cannot include filters on properties. They can, however, filter by Entity Key by passing Entity.KEY_RESERVED_PROPERTY as the property name for the filter. Ascending sorts on Entity.KEY_RESERVED_PROPERTY are also supported."




回答3:


This is a little late, however it will help anyone with the same problem.

The solution is to first do a keys-only query and take the subset of keys which are direct descendants.

With that subset of keys, you can batch get the desired entities.

I'm unfamiliar with python, so here's an example in go:

directDescKeys := make([]*datastore.Key, 0)

q := datastore.NewQuery("A").Ancestor(parentKey).KeysOnly()
for it := q.Run(ctx);; {
    key, err := it.Next(nil)
    if err == datastore.Done {
        break
    } else if err != nil {
        // handle error
    }

    if reflect.DeepEquals(key.Parent(), parentKey) {
        directDescKeys = append(directDescKeys, key)
    }
}

entities := make([]*A, len(directDescKeys))
if err := datastore.GetMulti(ctx, directDescKeys, entities); err != nil {
    // handle error
}


来源:https://stackoverflow.com/questions/10219137/how-can-i-query-for-direct-descendants-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!