Query random row in ndb [closed]

只愿长相守 提交于 2019-12-29 09:10:27

问题


I am trying to develop an web app on google app engine using webapp2.

One of the thing I need to do is to retrieve a random from ndb and display it. Is it any effective method that allows me to do so?


回答1:


I assume you mean a random record when you say "random from ndb".

If you are using automatic id's you could use the following approach. (how sparse you id's will affect how successful this will be).

use random.randrange(start, stop) with start being 0, stop being (2^52)-1 , given the new id allocation policy.

do a keys only query for keys greater than key created from random id. if no results try getting keys < key created.

fetch 10 (or some number) of keys

do a random choice random.choice(seq) on the sequence of keys returned from the earlier fetch.

key.get() the chosen record.

The alternative for a small number of entities say < 1000

do a keys only query and fecth all the keys, then do a random.choice() on the list of keys and the a db.get() on the chosen key. This will be much quicker than any looping solution. If you do this a lot and the set of entities to choose from do not change to frequently and the list of keys is less than 1MB in size, you could cache the keys in memcache.




回答2:


There's a scatter reserved property. I don't know much about it, but it's mentioned in the map/reduce implementation.




回答3:


If the number of entities in your datastore is not very large, then you can use the below approach: 1, Use yourquery = entitykind.query() to fetch all entities

2, Use yourquery.count() to get the number of entities

3, Use a random number generator to create a random number within the above count value

4, Use a for loop to iterate through the entities returned by

yourquery.fetch()

and then when the number of times the loop has been executed equals the above random number, use the particular entity in your webapp



来源:https://stackoverflow.com/questions/17289752/query-random-row-in-ndb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!