views:

96

answers:

2

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?

A: 

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
The 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