How can I request only direct descendants?

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

entity a is the parent of object b; object b is the parent of c

Now, if I make the following request

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

The result will contain both objects b and c. Is there any way I can filter c so that only entities that are direct descendants remain? In any case, besides me, I mean the results and their removal.

+6
source share
3 answers

The only way to do this is to change your schema by adding a β€œparent” KeyProperty that references the direct parent and then filters it.

+4
source

Actually, this is not supported at all. Nick's answer works, but only if you can specify the type of object in the request that the OP did not specify:

"Useless queries cannot include filters by properties, but they can filter by Entity Key by passing Entity.KEY_RESERVED_PROPERTY as the property name for the filter. Upstream sorts on Entity.KEY_RESERVED_PROPERTY are also supported."

+1
source

This is a bit late, however it will help anyone who has the same problem.

The solution is to first execute the query only for keys and take a subset of the keys that are direct descendants.

With this subset of keys, you can batch get the right objects.

I am not familiar with python, so here is 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 } 
0
source

Source: https://habr.com/ru/post/913581/


All Articles