Redis sorted set and solving ties

你。 提交于 2019-12-06 06:57:12

问题


I'm using a Redis sorted set to store a ranking for a project I'm working on. We hadn't anticipated (!) how we wanted to handle ties. Redis sorts lexicographically the entries that have the same score, but what we want to do is instead give the same rank to all the entries that have the same score, so for instance in the case of

redis 127.0.0.1:6379> ZREVRANGE foo 0 -1 WITHSCORES
1) "first"
2) "3"
3) "second3"
4) "2"
5) "second2"
6) "2"
7) "second1"
8) "2"
9) "fifth"
10) "1"

we want to consider second1, second2 and second3 as both having position 2, and fifth to have position 5. Hence there is no entry in the third or fourth position. ZREVRANK is not useful here, so what's the best way to get the number I'm looking for?


回答1:


It seems to me one way is writing a little Lua script and use the EVAL command. The resulting operation has still logarithmic complexity.

For example, suppose we are interested in the position of second2. In the script, first we get its score with ZSCORE, obtaining 2. Then we get the first entry with that score using ZRANGEBYSCORE, obtaining second3. The position we're after is then ZREVRANK of second3 plus 1.

redis 127.0.0.1:6379> ZSCORE foo second2
"2"
redis 127.0.0.1:6379> ZREVRANGEBYSCORE foo 2 2 LIMIT 0 1
1) "second3"
redis 127.0.0.1:6379> ZREVRANK foo second3
(integer) 1

So the script could be something like

local score = redis.call('zscore', KEYS[1], ARGV[1])
if score then
  local member = redis.call('zrevrangebyscore', KEYS[1], score, score, 'limit', 0, 1)
  return redis.call('zrevrank', KEYS[1], member[1]) + 1
else return -1 end


来源:https://stackoverflow.com/questions/14944279/redis-sorted-set-and-solving-ties

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