我正在尝试使用webapp2在谷歌应用程序引擎上开发一个Web应用程序。
我需要做的一件事是从ndb中检索一个随机数并显示它。是否有任何有效的方法可以让我这样做?
NDB。
如果您使用的是自动编号,您可以使用以下方法。 (如何稀疏你的id会影响这将是多么成功)。
使用 random.randrange(start,stop)开始为0,在给定新的id分配策略的情况下停止为(2 ^ 52)-1。
对大于关键字的键随机ID。如果没有结果尝试获取密钥<键创建。 获取10(或某些数字)的键
随机选择 random.choice(seq)对从先前获取返回的键序列进行操作。
key.get()所选记录。
少数实体的替代方案称< 1000
做一个关键字的查询和所有关键字,然后在关键字上做一个 random.choice()关键字列表和所选键上的db.get()。这将比任何循环解决方案快得多。如果您这样做了很多,并且可供选择的实体集不会经常更改,并且键列表的大小小于1MB,您可以将键缓存在memcache中。
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?
解决方案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.
更多推荐
在ndb中查询随机行
发布评论