redisleaderboardsortedset

Redis sorted set leader board ranking on same score


I'm using Redis sorted set to implement the leaderboard of my game, where I show the user ranking in descending order. I'm stuck in a case where two or more users have the same score. So in this case, I want the higher ranking of the user who gets the score first. For example, I'm adding the following entries in Redis.

127.0.0.1:6379> zadd testing-key 5 a
(integer) 1
127.0.0.1:6379> zadd testing-key 4 b
(integer) 1
127.0.0.1:6379> zadd testing-key 5 c
(integer) 1

and when I'm querying for the rank in reverse order, I'm getting this

127.0.0.1:6379> zrevrange testing-key 0 10
1) "c"
2) "a"
3) "b"

but in my case, the ranking should be like

1) "a"
2) "c"
3) "b"

So is there any provision in Redis to give higher precedence to the entity which entered first in the set with the same score?


Solution

  • I found one solution to this problem. In my case, the score is an integer so I converted it into decimal and added Long.MAX_VALUE - System.nanoTime() after decimal. So the final score code will be like

    double finalScore = score.(Long.MAX_VALUE - System.nanoTime());
    

    So the final score of the player who scored first would be higher than the second one. Please let me know if you have any better solution.