[英]Rails query random records using weights
假设我有一个型号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
我该如何进行此查询?
根据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
如您所见,分布符合预期
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.