Raj
Raj

Reputation: 22926

Redis: Group & Sum multiple ZSET Sorted Sets into one Sorted Set

If I have two sorted set with different set of members with different scores:

ZADD set1 10 "player1"
ZADD set1 15 "player2"
ZADD set1 5 "player3"

ZADD set2 30 "player1"
ZADD set2 22 "player3"

I need to merge the above 2 sets by grouping the common all players and summing up their scores and get like this:

set3 40 "player1"
set3 15 "player2"
set3 27 "player3"

One way I tried is to fetch this data into Ruby objects and do the grouping logic. I am looking for ways to do this within Redis.

Upvotes: 3

Views: 1658

Answers (1)

Not_a_Golfer
Not_a_Golfer

Reputation: 49205

You're in luck because redis supports this out of the box!

ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX]

summary: Intersect multiple sorted sets and store the resulting sorted set in a new key

so in your case:

ZINTERSTORE set3 2 set1 set2 AGGREGATE SUM

and voila! set3 contains the common players with summed scores:

127.0.0.1:6379> ZRANGE set3 0 -1 WITHSCORES
1) "player3"
2) "27"
3) "player1"
4) "40"

Upvotes: 7

Related Questions