I have a datastore with around 1,000,000 entities in a model. I want to fetch 10 random entities from this.
I am not sure how to do this? can someone help?
I have a datastore with around 1,000,000 entities in a model. I want to fetch 10 random entities from this.
I am not sure how to do this? can someone help?
Assign each entity a random number and store it in the entity. Then query for ten records whose random number is greater than (or less than) some other random number.
This isn't totally random, however, since entities with nearby random numbers will tend to show up together. If you want to beat this, do ten queries based around ten random numbers, but this will be less efficient.
Here's another not-so-random approach:
1. fetch some records, and
2. pull a random sample from records fetched.
import random
N = 3
TO_FETCH = 10
results = MyModel.all().fetch(TO_FETCH)
results = random.sample(results, N)
self.response.out.write(template.render(path, {'results': results,}))