![](/img/trans.png)
[英]How to find the (n) keys with the highest values in a dictionary and store these in a set?
[英]Find the top N keys with highest values in Redis
我有 Redis 數據庫和user_id: rating
結構,我需要獲得 N 個具有最高評級(值)的用戶,例如:
u_345: 198
u_144: 180
u_267: 179
我的想法是:獲取所有鍵的列表,並為每個鍵獲取其值( db.mget(db.keys())
),然后按值排序並獲得第一個 N。有沒有更好的方法?
我使用redis-py Python 庫。 但最主要的是獲得正確的算法(或現成的解決方案)。
看來您應該遵循使用 Sorted Set 作為二級索引的模式。
你應該使用ZRANGE
( https://redis.io/commands/zrange/ )。
使用您的數據集,您可以使用這種方法:
ZADD ratingindex 198 u_345
ZADD ratingindex 180 u_144
ZADD ratingindex 179 u_267
然后,要檢索具有最高值的 2(或 N)鍵,您應該使用:
ZRANGE ratingindex 0 1 withscores rev
此命令將從ratingindex
中檢索兩個鍵(從 0 到 1),其值( withscores
)從最高到最低( rev
)排序。
最后你只需要將這個直接命令修改為 redis-py 庫。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.