Redis zrevrangebyscore, sorting other than lexicographical order

一曲冷凌霜 提交于 2019-12-03 20:33:03

The score in a sorted set supports double precision floating point numbers, so possibly a better solution would be to store the redis score as highscore.timestamp

e.g. (pseudocode)

highscore = 100
timestamp = now()
redis.zadd('myleaderboard', highscore + '.' + timestamp, playerId)

This would mean that multiple players who achieved the same high score will also be sorted based on the time they achieved that high score as per the following

For player 1...

redis.zadd('myleaderboard', '100.1362345366', "Charles")

For player 2...

redis.zadd('myleaderboard', '100.1362345399', "Babbage")

See this question for more detail: Unique scoring for redis leaderboard

The external weights feature of the sort command is your saviour here


SORT mylist BY weight_*

http://redis.io/commands/sort

If you are displaying leaderboard in descending order of score then I don't think the above solution will work. Instead of just appending timestamp in the score you should append Long.MAX_VALUE - System.nanoTime() So your final score code should be like -

highscore = 100
timestamp = Long.MAX_VALUE - System.nanoTime();
redis.zadd('myleaderboard', highscore + '.' + timestamp, playerId);

Now you will get the correct order when you call redis.zrevrange('myleaderboard', startIndex, endIndex)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!