【问题标题】:Rails query random records using weightsRails 使用权重查询随机记录
【发布时间】:2015-10-08 05:29:00
【问题描述】:

假设我有一个模特Product

有产品

id | title   | weight (integer)
1  | Sugar   | 1
2  | Salt    | 1
3  | Pepper  | 2
4  | Coke    | 5

所以,我想使用权重获得少数(比如说 2 个)随机产品。

Product.limit(2).rand_with_weights # =>
# The probability of coke is in array is 5x times bigger than salt or sugar and 2.5x times bigger than pepper
# The probability of pepper is in array is 2x times bigger than salt or sugar
# The probability of salt or sugar in array is equal

如何进行此查询?

【问题讨论】:

  • 您要随机查询吗?
  • 我想使用权重查询随机记录
  • 试试这个Product.order("RANDOM()*weight").limit(2)
  • @Pavan 如何正确理解结果?

标签: ruby-on-rails ruby postgresql activerecord


【解决方案1】:

根据 Efraimidis 和 Spirakis 的论文: https://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf

如果您使用的是 postgres:

Product.order("RANDOM() ^ (1.0 / weight) DESC").limit(2)

概念证明:http://sqlfiddle.com/#!17/474d2/4/0

如您所见,分布符合预期

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2014-08-04
    • 2015-12-20
    相关资源
    最近更新 更多