如何组合排序集Redis? [英] How combine the sorted sets Redis?
问题描述
我在 Redis 存储中使用 sorted set
类型.我为每个用户创建一个自己的 KEY 并将数据放在这里:
I use sorted set
type in Redis store.
For each user I create a own KEY and put here data:
KEY 示例:
FEED:USER:**1**, FEED:USER:**2**, FEED:USER:**3**
我想从 Redis 中为用户的键选择数据:1、2、3,并按分数(时间戳)对每个数据进行排序.
I want to select data from Redis for user's keys: 1, 2, 3 and sorted each by score (timestamp).
如果简单地看问题,我需要从任何 KEY 中选择一个跨时间的数据,然后将所有结果按分数排序.
If see at problem simply, I need select from any KEY a data across time and after combine all results sorted by score.
推荐答案
有几种方法可以做到这一点,但正确的方法取决于您要尝试做什么.例如:
There are a couple of ways to do this but the right one depends on what you're trying to do. For example:
- 您可以在代码中为每个
FEED:USER:n
键使用 ZRANGEBYSCORE(或 ZREVRANGEBYSCORE)并合并"客户端中的回复 - 您可以对相关键执行 ZUNIONSTORE,然后对客户端的结果执行 ZRANGEBYSCORE.
- 但是,如果您的提要"很大,则应该反转 #2 的流程 - 首先是范围,然后是联合.
- 您还可以使用一些 Lua 脚本完全在服务器端执行类似类型的处理.
- You can use ZRANGEBYSCORE (or ZREVRANGEBYSCORE) in your code for each
FEED:USER:n
key and "merge" the replies in the client - You can do a ZUNIONSTORE on the relevant keys and then do the ZRANGEBYSCORE on the result from the client.
- However, if your "feeds" are large, #2's flow should be reversed - first range and then union.
- You could also do similar types of processing entirely server-side with some Lua scripting.
进一步说明
再.1 - 合并可以在客户端根据您从 ZRANGEBYSCORE 获得的结果完成,或者您可以使用服务器端 Lua 脚本来执行此操作.使用 WITHSCORES 获取时间戳并对其进行合并/排序.无论您选择运行此代码的位置(我可能会使用 Lua 进行数据本地化),实现取决于您 - 如果您需要帮助,请使用 lmk :)
Re. 1 - Merging could be done client-side on the results that you get from ZRANGEBYSCORE or you could use server-side Lua scripts to do that. Use the WITHSCORES to get the timestamp and merge/sort on it. Regardless the your choice of location for running this code (I'd probably use Lua for data locality), the implementation is up to you - lmk if you need help with that :)
这篇关于如何组合排序集Redis?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!