Redis 动态排序 [英] Dynamic sort with Redis
问题描述
假设我的 Redis 数据库中有 5 个条目:
Let's say I have 5 entries in my Redis database:
news::id
:最后一条新闻的ID;news::list
:所有新闻ID的列表;news:n
其中 n 是新闻 ID:一个包含title
、url
等字段的哈希值等;news:n:upvotes
:所有为新闻点赞的用户 ID 的列表,从而给出了点赞数.news:n:downvotes
:所有对新闻投反对票的用户 ID 的列表,从而给出投反对票的数量.
news::id
: the ID of the last news;news::list
: a list of all news IDs;news:n
where n is the news ID: a hash containing fields such astitle
,url
, etc.;news:n:upvotes
: a list of all users' IDs who upvoted the news, thus giving the number of upvotes.news:n:downvotes
: a list of all users' IDs who downvoted the news, thus giving the number of downvotes.
然后我有多种排名算法,其中 rank =
:
Then I have multiple ranking algorithms, where rank =
:
upvotes_count
;upvotes_count - downvotes_count
;upvotes_count - downvotes_count - 年龄
;upvotes_count/downvotes_count
;年龄
.
现在我如何根据这些算法对这些新闻进行排序?
Now how do I sort those news according to each of these algorithms?
我想过计算每张选票的不同排名,但是如果我引入一种新算法,我需要计算所有新闻的新排名.
I thought about computing the different ranks on every votes, but then if I introduce a new algorithm I need to compute the new rank for all the news.
EVAL
可能会有所帮助,但要到 v2 才能使用.6,我当然不想等.
EVAL
could help but it won't be available until v2.6, which surely I don't want to wait for.
最终,我可以检索所有新闻并将它们放入 Python 列表中.但它再次转化为高内存使用率,更不用说Redis将其数据存储在内存中这一事实.
Eventually, I could retrieve all the news and put them in a Python list. But again it translates into a high memory usage, not to mention the fact that Redis stores its data in memory.
那么有没有合适的方法来做到这一点,还是我应该转移到 MongoDB?
So is there a proper way to do this or should I just move to MongoDB?
推荐答案
您可以按存储在键中的常量进行排序.
You can sort by constants stored in keys.
在您的示例中,我几乎可以使用 Redis 对 1.
进行排序.如果您在计算后存储其他表达式值,您也可以按它们排序.对于 1.
,您需要将列表计数存储在某处,我假设 news:n:upvotes:count
.
In your example, I can sort 1.
almost trivially using Redis. If you store the other expression values after calculating them, you can sort by them too. For 1.
, you will need to store the list count somewhere, I will assume news:n:upvotes:count
.
问题在于使用 SORT 命令.例如,第一种排序是:
The catch is to use the SORT command. For instance, the first sort would be:
SORT news::list BY news:*:upvotes:count GET news:*->title GET news:*->url
...获得按赞数排序的标题和网址,按新月顺序排列.
...to get titles and urls sorted by upvotes, in crescent order.
也有修饰符,用于alpha
排序和asc/desc
排序.完整阅读命令页面,值得.
There are modifiers too, for alpha
sorting, and asc/desc
sorting. Read the command page entirely, it is worthwhile.
PS:您可以在 MULTI/中包装计数、存储、排序和可能的删除计数EXEC 环境(一个事务).
PS: You can wrap the count, store, sort and possibly deletion of count in a MULTI/EXEC environment (a transaction).
这篇关于Redis 动态排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!