Redis排序集和解决联系

Redis排序集和解决联系

本文介绍了Redis排序集和解决联系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Redis排序集来存储我正在处理的项目的排名.我们没想到(!)我们想如何处理关系. Redis按字典顺序对具有相同分数的条目进行排序,但是我们要做的是为具有相同分数的所有条目赋予相同的排名,例如对于

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"

我们要考虑second1second2second3都具有位置2,并且fifth都具有位置5.因此,在第三或第四位置没有条目. ZREVRANK在这里没有用,那么获取我正在寻找的电话号码的最佳方法是什么?

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?

推荐答案

在我看来,一种方法是编写一些Lua脚本并使用EVAL命令.结果运算仍然具有对数复杂性.

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

例如,假设我们对second2的位置感兴趣.在脚本中,首先使用ZSCORE获得其得分,获得2.然后使用ZRANGEBYSCORE获得具有该得分的第一个条目,获得second3.那么我们所追求的位置就是second3ZREVRANK加1.

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

所以脚本可能像

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

这篇关于Redis排序集和解决联系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 03:26