When should I use ndb.KeyProperty vs. ancestors?
Asked Answered
R

1

11

In AppEngine's NDB datastore, it seems there are 2 ways to relate objects with one another. There's ndb.KeyProperty and parents/ancestors keys. I'm a bit confused as to when I should be using one or the other?

Right now I've been using KeyProperty exclusively, since it's the most familiar one, but I want to know when one is a better fit than the other.

Rochester answered 6/11, 2013 at 3:3 Comment(0)
E
17

Ancestors are hierarchical - they can be used when you have hierarchical relationships between things (for instance, in a forum system you might have Forums which have Topics which in turn have Posts).

KeyProperty is not inherently hierarchical - it just provides a link. It should be used for non-hierarchical linkages between items. Reusing the forum example from the previous paragraph, one might use a KeyProperty to link a Post to the User who created it - because Users aren't in the forum-topic-post hierarchy. They're related to all 3 (for instance, a User might create a post, create a topic, and/or moderate a forum).

In the end, however, the main tradeoff between ancestors and keys is in consistency vs. throughput: ancestor-based queries give you strong consistency relative to recent updates, but impose a limit of 1 modification per second for any given entity group and a maximum size limit for the group due to lack of distribution.

Elmore answered 6/11, 2013 at 3:17 Comment(2)
Also note when using ancestors to define a heirarchy it is fixed. You can't move children around, so if you want to be able move entities in the heirarchy you would use KeyProperties,. Also note you can specify an ancestor in a key but the ancestor does not have to exist.Shakiashaking
Also there is a maximum size you can store under an ancestor because it will not be distributed (and thats also why it has strong consistency).Parchment

© 2022 - 2024 — McMap. All rights reserved.