查询ndb中的随机行 [英] Query random row in ndb

查看:29
本文介绍了查询ndb中的随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 webapp2 在谷歌应用引擎上开发一个网络应用.

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

我需要做的一件事是从 ndb 中检索随机数并显示它.有什么有效的方法可以让我这样做吗?

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?

推荐答案

当您说来自 ndb 的随机"时,我假设您指的是随机记录.

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

如果您使用自动 ID,您可以使用以下方法.(您的 id 的稀疏程度将影响这将如何成功).

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).

使用 random.randrange(start, stop) 开始为 0,停止为 (2^52)-1 ,给定新的 id 分配策略.

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

只查询大于从随机 id 创建的密钥的密钥.如果没有结果,请尝试获取密钥 <密钥已创建.

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

获取 10 个(或一些)密钥

fetch 10 (or some number) of keys

对从早期获取返回的键序列进行随机选择 random.choice(seq).

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

key.get() 选择的记录.

key.get() the chosen record.

少数实体的替代方案是 <1000

The alternative for a small number of entities say < 1000

只查询并处理所有的键,然后在键列表上执行 random.choice() 并在所选键上执行 db.get().这将比任何循环解决方案快得多.如果您经常这样做并且要从中选择的实体集不经常更改并且键列表的大小小于 1MB,则可以将键缓存在 memcache 中.

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中的随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆