6

Are the children of an entity available in a Query?

Given:

class Factory(db.Model):
    """ Parent-kind """
    name = db.StringProperty()

class Product(db.Model):
    """ Child kind, use Product(parent=factory) to make """
    @property
    def factory(self):
        return self.parent()
    serial = db.IntegerProperty()

Assume 500 factories have made 500 products for a total of 250,000 products. Is there a way to form a resource-efficient query that will return just the 500 products made by one particular factory? The ancestor method is a filter, so using e.g. Product.all().ancestor(factory_1) would require repeated calls to the datastore.

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
Thomas L Holaday
  • 13,614
  • 6
  • 40
  • 51

1 Answers1

8

Although ancestor is described as a "filter", it actually just updates the query to add the ancestor condition. You don't send a request to the datastore until you iterate over the query, so what you have will work fine.

One minor point though: 500 entities with the same parent can hurt scalability, since writes are serialized to members of an entity group. If you just want to track the factory that made a product, use a ReferenceProperty:

class Product(db.Model):
   factory = db.ReferenceProperty(Factory, collection_name="products")

You can then get all the products by using:

myFactory.products
mcobrien
  • 1,130
  • 1
  • 9
  • 16
  • The docs call it a filter, but it isn't? Mercy sakes, what next. The use case for writes is each Factory creates zero to ten Products / day with a minimum time between products of ten seconds ("bursty"). 95% of Product reads will be Factory-as-a-whole. Is parent-child or ReferenceProperty better? – Thomas L Holaday Feb 14 '09 at 17:53
  • I think the recommendation is to use entity groups from transactions only, so a ReferenceProperty would be better, although there probably isn't a huge difference... – mcobrien Feb 17 '09 at 08:35
  • There's nothing wrong with 500 elements in the same entity group - it's the update rate that counts. – Nick Johnson Apr 01 '09 at 10:27
  • Why would you use ancestor queries rather than a reference property? I'm finding myself I want to check for the existence of a property (inequality filter != null) over a range of entities with a reference property (equality filter). I can't do that without an index! and I could have 100,000 entities to search through. So adding an ancestor (rather than the reference prop ) would perhaps allow me to perform that query without an extra index – ZiglioUK Dec 18 '13 at 03:19