How combine the sorted sets Redis?

2019-09-06 17:48发布

I use sorted set type in Redis store. For each user I create a own KEY and put here data:

Example of KEY:

FEED:USER:**1**, FEED:USER:**2**, FEED:USER:**3**

I want to select data from Redis for user's keys: 1, 2, 3 and sorted each by score (timestamp).

If see at problem simply, I need select from any KEY a data across time and after combine all results sorted by score.

标签: php redis
1条回答
成全新的幸福
2楼-- · 2019-09-06 18:33

There are a couple of ways to do this but the right one depends on what you're trying to do. For example:

  1. You can use ZRANGEBYSCORE (or ZREVRANGEBYSCORE) in your code for each FEED:USER:n key and "merge" the replies in the client
  2. You can do a ZUNIONSTORE on the relevant keys and then do the ZRANGEBYSCORE on the result from the client.
  3. However, if your "feeds" are large, #2's flow should be reversed - first range and then union.
  4. You could also do similar types of processing entirely server-side with some Lua scripting.

EDIT: further clarifications

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 :)

查看更多
登录 后发表回答