六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 194|回复: 0

GAE 随机获取实体

[复制链接]

升级  11.82%

1179

主题

1179

主题

1179

主题

榜眼

Rank: 8Rank: 8

积分
3591
 楼主| 发表于 2013-2-7 21:15:00 | 显示全部楼层 |阅读模式
有时我们需要随机地获取数据记录(实体),比如博客程序中的“随机文章”的实现。
目前 GAE 并没有 API 可以直接获取随机实体,要实现这样的需求我们只能自己想办法了 :-)
在 stackoverflow 上也有人提过该问题,总结如下:


  • Generate and store a random number on your entities as you create them, then pick a random number and look (via a query) for the closet record(s) to it.
  • Implement some mechanism to ensure your entity ids are "densely" populated, then fetch within the known range using keys.
  • Periodically generate random lists of the entities and return entities from those lists.  This may take the form of a stack that entities are popped off of, or as actual lists that are returned.
目前 B3log Solo 在处理“随机阅读”上采用的是方法一,即在每个文章实体上添加一个属性保存 0-1 的随机浮点数。
在获取随机文章时生成一个 0-1 的随机数(mid)作为查询条件,以此查询条件作为边界(0
这个方法基本可以达到随机的效果了,为了让随机的效果更动态一点,我们可以考虑经常更新文章实体中的随机浮点值:

  • 访问文章时(即在更新文章浏览次数时一并更新该文章的随机浮点值)
  • 后台定时任务(获取一定数量的随机文章然后更新它们的随机浮点值)
  • 用户做文章更新时
加上以上处理后,随机的效果比较好了 :-)


<div style="">本文是使用 B3log Solo简约设计の艺术 进行同步发布的
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表