Search code examples
redisnumericalsortedset

Redis SortedSet: How to get values in numerical order rather than alphabetical order when two values has the same score?


Recently, I'm using redis SortedSet to implement game rank for every user, but I've got a problem:

zadd game_rank 55 6435
zadd game_rank 55 6088561
zadd game_rank 55 608825
zrange game_rank 0 -1

the result is :

"60882561"
"608852"
"6435"

I want to know if it's possible to get the values in numerical order when in same score:

"6435"
"608852"
"60882561"

Solution

  • When a sorted set's members have the same score, they are sorted lexicographically. There's no straightforward way to get them ordered differently AFAIK but you can easily do the sorting on the client's side. Alternatively, you could cook up a short Lua script that does that for you on the server.

    There is a slightly hackish way that you can get away with what you want without resorting to the approaches above. Based on the example you had provided and ssuming that both rank and user id are integers, you could use scores that are a combination of both, like so:

    zadd game_rank 550006435 6435
    zadd game_rank 556088561 6088561
    zadd game_rank 550608825 608825
    

    This will let you do ranges and you'll get "numerical" sorting for each rank (i.e. with zrangebyscore game_rank 550000000 559999999).