skip to Main Content

I have 2 sorted set acting as ranking. I want to get the top 5 from the union between them. the scores are the same.

zadd rank1 1 aaa
zadd rank1 2 bbb
zadd rank1 3 ccc
zadd rank1 4 ddd
zadd rank2 1 aaa
zadd rank2 2 bbb
zadd rank2 3 ccc
zadd rank2 4 ddd

What is the best approach to do so?

ZUINON 10 rank1 rank2 AGGREGATE MAX 5 

I would assume something like that, but max 5 doesn’t exists.

EDIT
Just figured out that even ZUNION wouldn’t help as my redis version is 6.0.5 and not 6.2.0

2

Answers


  1. It depends on what you would like to do with the scores of the same key. For the two ‘aaa’, do you want to add them (aggregate) and then get the top five aggregated result?

    You can use ZUNIONSTORE, with the option of storing the temporary result somewhere else, and then get the top five result. (supports Redis version below 6)

    To do this atomically, you’ll need a lua script to combine the following two commands

    ZUNIONSTORE out 2 rank1 rank2  --(the temporary result is stored in a zset called 'out')
    ZREVRANGE out  0 4   ---- (ranking from highest to lowest, get top five)
    
    Login or Signup to reply.
  2. my sorted sets are huge – i.e million of keys in each set. plus, this union will happen a lot of times per sec (it is the top query in my site). is this the fastest approach?

    Just take the top 5 from each SortedSet and choose top 5 among those 10 elements at your server(/client) process. This would be the fastest and least complex for your scenario.

    You can get top N elements from one SortedSet using ZREVRANGE command. But to unify/merge 2xN elements and choose top M elements, you would also require the respective scores of those elements. ZREVRANGE command with WITHSCORES keyword returns top N elements with their scores.

    ZREVRANGE rank1 0 4 WITHSCORES
    ZREVRANGE rank2 0 4 WITHSCORES
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search