在ndb中查询随机行

编程入门 行业动态 更新时间:2024-10-17 13:27:43
本文介绍了在ndb中查询随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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中查询随机行

本文发布于:2023-11-22 06:33:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616333.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ndb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!