Pretty simple, in my AppEngine application, I have over 1 million entities of one kind, what is the best way to pick one at random?
Asked
Active
Viewed 1,664 times
4

Lucas Zamboulis
- 2,494
- 5
- 24
- 27

Noah McIlraith
- 14,122
- 7
- 31
- 35
-
1possible duplicate of [How to get something random in datastore (AppEngine)?](http://stackoverflow.com/questions/3450926/how-to-get-something-random-in-datastore-appengine) – David Underhill Sep 12 '10 at 18:00
-
1possible duplicate of [Fetching a random record from the Google App Engine Datastore?](http://stackoverflow.com/questions/3002999/fetching-a-random-record-from-the-google-app-engine-datastore) – Nick Johnson Sep 13 '10 at 10:21
-
Possible duplicate of [Fetching a random record from the Google App Engine Datastore?](https://stackoverflow.com/questions/3002999/fetching-a-random-record-from-the-google-app-engine-datastore) – clickbait Jul 31 '18 at 17:21
-
Possible duplicate of [How to get something random in datastore (AppEngine)?](https://stackoverflow.com/questions/3450926/how-to-get-something-random-in-datastore-appengine) – Saxon Druce Aug 01 '18 at 01:53
2 Answers
0
Maybe one solution but i don't know if it's the best :)
import random
from google.appengine.ext import db
from google.appengine.api import memcache
DATA_KEY = "models/keys/random"
def get_data():
data = memcache.get (DATA_KEY)
if data is None:
offset = random.randint (1, 1000000)
data = self.MyModel.all (keys_only=True).fetch (100, offset)
memcache.add (DATA_KEY, data, 60)
entity_key = random.choice (data)
return db.get (entity_key)

sahid
- 2,570
- 19
- 25
-
1The fetch will take increasing time as the size of the offset increases. You should expect a DeadlineExceeded exception on nearly every request with this code. – Wooble Sep 12 '10 at 13:02
-1
See this question:
Fetching a random record from the Google App Engine Datastore?

Community
- 1
- 1

Saxon Druce
- 17,406
- 5
- 50
- 71
-
1@sag I don't know why 2010 me put this as an "answer" instead of voting to close as a duplicate - I'll do that now. – Saxon Druce Aug 01 '18 at 01:53