Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get something random in datastore (AppEngine)?

Currently i'm using something like this:

    images = Image.all()
    count = images.count()
    random_numb = random.randrange(1, count)
    image = Image.get_by_id(random_numb)

But it turns out that the ids in the datastore on AppEngine don't start from 1. I have two images in datastore and their ids are 6001 and 7001.

Is there a better way to retrieve random images?

like image 875
user216171 Avatar asked Aug 10 '10 15:08

user216171


1 Answers

The datastore is distributed, so IDs are non-sequential: two datastore nodes need to be able to generate an ID at the same time without causing a conflict.

To get a random entity, you can attach a random float between 0 and 1 to each entity on create. Then to query, do something like this:

rand_num = random.random()
entity = MyModel.all().order('rand_num').filter('rand_num >=', rand_num).get()
if entity is None:
  entity = MyModel.all().order('rand_num').get()

Edit: Updated fall-through case per Nick's suggestion.

like image 161
Drew Sears Avatar answered Sep 30 '22 08:09

Drew Sears