Checking whether specified multiple keys exist in Datastore table without fetching the entity

I have let's say 1000 key names whose existance I want to check in the Google App Engine datastore, but without fetching the entities themselves. One of the reason, beside possible speedups, is that keys-only fetching is free (no cost).

ndb.get_multi() allows me to pass in the list of keys, but it will retrieve the entities. I need a function to do just that but without fetching the entities, but just True or False based whether the specified keys exist.

Upvotes: 1

Views: 406

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881555

I'd probably use a keys-only query...:

q = EntityKind.query(EntityKind.key.IN(wanted_keys))
keys_present = set(q.iter(keys_only=True))

That gives you keys_present as a set of those keys in wanted_keys that are actually present in the datastore. Not quite the same as your desired mapping from key to bool, but, the latter can be easily built:

key_there = {k: (k in keys_present) for k in wanted_keys}

...should you actually want it (a dict with bool values is usually more likely to be a less-wieldy hack for a set!-).

Upvotes: 2

Related Questions