Search code examples
redisleaderboard

Redis sorted set variadic leaderboard


I'm trying to set up a leaderboard with a wins over losses format. Example, 10/20 would be 10 wins and 20 losses. I'm using redis and would like to use sorted sets. How can I have redis sort it by the wins, but also return the losses?

I found this on the redis website:

"

> zadd hackers 1940 "Alan Kay"
(integer) 1
> zadd hackers 1957 "Sophie Wilson"
(integer) 1
> zadd hackers 1953 "Richard Stallman"
(integer) 1
> zadd hackers 1949 "Anita Borg"
(integer) 1
> zadd hackers 1965 "Yukihiro Matsumoto"
(integer) 1
> zadd hackers 1914 "Hedy Lamarr"
(integer) 1
> zadd hackers 1916 "Claude Shannon"
(integer) 1
> zadd hackers 1969 "Linus Torvalds"
(integer) 1
> zadd hackers 1912 "Alan Turing"
(integer) 1

As you can see ZADD is similar to SADD, but takes one additional argument (placed before the element to be added) which is the score. ZADD is also variadic, so you are free to specify multiple score-value pairs, even if this is not used in the example above.

"

I'm having trouble finding an example of variadic usage. Is that a way to add 2 scores to one element? Like zadd hackers 1940 1945 "alan kay"?

I'm thinking a hash might be a better solution, but then I'd have to sort it elsewhere.

My main question: How can I use redis to sort a leaderboard by wins and losses?


Solution

  • The "variadic" part of ZADD refers to its ability to set multiple score-element pairs in one call. Sorted Sets' elements always have one and only one score.

    You could, however, keep two Sorted Sets, one for wins and the other one for losses.