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
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
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 withWITHSCORES
keyword returns top N elements with their scores.