Retrieve random object from data store

Quite simply, in my AppEngine app I have over 1 million objects of the same kind, what's the best way to pick them at random?

+3
source share
2 answers

Maybe one solution, but I don't know if this is better :)

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)
-1
source

Source: https://habr.com/ru/post/1764350/


All Articles