Question

Possible Duplicate:
Fetching a random record from the Google App Engine Datastore?

How can I efficiently pick a random database record using GQL?

Eg. I have a Quotes Model and I need to pick a random quote every time. The question follows from my understanding that the ID attribute cannot be guaranteed to be auto-incremented with every insertion in the production server.

Was it helpful?

Solution

The auto-generated ids are guaranteed to be unique, but not sequential or strictly increasing.

There are already many questions about this on stackoverflow, and in the groups.

There are several common solutions:

  • Generate and store a random number on your entities as you create them, then pick a random number and look (via a query) for the closet record(s) to it.
  • Implement some mechanism to ensure your entity ids are "densely" populated, then fetch within the known range using keys.
  • Periodically generate random lists of the entities and return entities from those lists. This may take the form of a stack that entities are popped off of, or as actual lists that are returned.

What you do not want to do is choose a random offset. Offset is very inefficient because the datastore still has to scan over all of the skipped entities.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top