datastore 

Send to Kindle
home » snippets » appengine » datastore



Snippets

It's "generally" cheaper to fetch all the keys from a query (i.e. classifies as a small datastore op) and then a ndb.get_multi() to get those entities

From: Guido's comment on fetching from cache

q = MyModel.query(...)

results = ndb.get_multi(q.fetch(keys_only=True))

# Only get those entities that are in the cache.
results = ndb.get_multi(q.fetch(keys_only=True), use_datastore=False)


# Async version.
def cb(key):
    ent = key.get(use_datastore=False)  # or True
    if ent is not None:
      # ...do what you want with ent...

# and pass this to map, as follows:

yield q.map(cb, keys_only=True)

NDB examples

The Article class

Instances of class Article are used in the examples for Querying for Repeated Properties.

class Article(ndb.Model):
  title = ndb.StringProperty()
  stars = ndb.IntegerProperty()
  tags = ndb.StringProperty(repeated=True)

article = Article(title='Python versus Ruby',
                  stars=3,
                  tags=['python', 'ruby'])
article.put()

ANDs and ORs

Ref: Combining AND and OR Operations

All the filters are normalized into DNF form so this might cause a combinatorial explosion.

Beware that if your filters is mostly CNF like with lots of conjunctions, the transformation can be hude.  e.g. (A1∨B1)∧(A2∨B2)∧...∧(An∨Bn) → 2ⁿ entries.

Limits