Redis sorted set and solving ties

眉间皱痕 提交于 2019-12-04 10:44:59
idrarig

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