[英]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.