1

I used a slightly modified solution from this thread to get a set of randomly chosen items from Datastore. I use ProtoRPC, though it doesn't make much difference, just for your information. My code looks like this:

@remote.method(RandomImagesRequest, RandomImagesResponse)
def get_random_images(self, request):
    images = []
    count = request.count
    for i in range(0, count):
        random_number = random.random()
        img = Image.all().order('random_number').filter('random_number>=', random_number).get()
        if img is None:
            img = Image.all().order('-random_number').filter('random_number <', random_number).get()
        image_message = ImageMessage(image_url=img.image_url)
        images.append(image_message)
    return RandomImagesResponse(images=images)

This way I get any number of randomly chosen items. But sometimes there duplicates appear. How to effectively get only unique items from Datastore?

Community
  • 1
  • 1
Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335

2 Answers2

0

Instead of fetching N items separately, just do a fetch for three items where random_number >= the new random_number.

The downside is that you will occasionally get 0-2 items, in which case if you absolutely need 3 items you can re-fetch the rest with another random number (or switch the >= to a <)

Jason Hall
  • 20,632
  • 4
  • 50
  • 57
  • That method will work for one query, but you are dooming groups of items to often be selected together (assuming no new writes to the datastore), which reduces randomness. – Justin Morgan May 12 '11 at 20:10
  • 1
    To address this, reassign their random numbers when you fetch them. – Jason Hall May 12 '11 at 20:45
0

You could just check to make sure the entity's key is not in your images list before appending it, and requery if it is. Just make sure you have at least count items in the database or else it will loop infinitely.

Justin Morgan
  • 2,427
  • 2
  • 16
  • 19