Get random entity

740 views
Skip to first unread message

GAENewB

unread,
Apr 28, 2008, 12:40:17 PM4/28/08
to Google App Engine
Is their any way to get a random entity (record) from a declared
entity type?

Marce

unread,
Apr 28, 2008, 2:18:15 PM4/28/08
to Google App Engine
Hi,
Currently, there is no way to directly query a random entity, but one
of our engineers has taken the following approach:

If you want to be able to access a random entity for a certain object
model, you can do it in this way:

* When inserting the entity, have a field called "rand" (or any
other name), and store a random value between 0 and 1 when the entity
is created.
import random

class MyModel(db.Model):
rand = db.FloatProperty()
first_property = db.StringProperty()

main():
model = MyModel()
model.rand = random.random()
model.put()

* Make sure that the very first value entered has a value of 1.0
for this field. You can do this via a special case in the code, or by
manually editing it with the admin console.
* When querying, use the following GQL query: "SELECT * FROM
MyModel WHERE rand > :rand ORDER BY rand LIMIT 1", and bind a random
float to rand.

While you are not guaranteed that all entities will be equally likely
to appear, this should give a relatively good random distribution. It
also will scale, since there are no locks needed to get a uniformly
incrementing counter.

Hope this helps,
Marzia

Alex

unread,
May 5, 2008, 11:03:43 AM5/5/08
to Google App Engine
On 28 Kwi, 18:40, GAENewB <dean.ba...@gmail.com> wrote:
> Is their any way to get arandomentity (record) from a declared
> entity type?

You can get all records and then you should get a list of them and
simply choose one with random, like that:

class Story(db.Model):
body = db.StringProperty(multiline=True, required=True)
when = db.DateTimeProperty(auto_now_add=True)

class FrontPageHandler(webapp.RequestHandler):
def get(self):
stories = Story.all()

story = stories[random.randint(0, stories.count()-1)]
[..]

Wesley Tanaka

unread,
May 29, 2008, 6:19:12 PM5/29/08
to Google App Engine
A) You could avoid the special "1.0" entity by running a second
"wrapped around" query if the first query returned no results.

B) It also seems plausible that you'd want to update rand with a new
value every time you happened to be writing one of the entities to the
database anyway to smooth out the distribution over time.

But I'm not sure if it would incur an extra index update CPU hit.
Reply all
Reply to author
Forward
Message has been deleted
0 new messages