Hassan Baig
Hassan Baig

Reputation: 15824

From redis sorted set, retrieving the rank of the highest value that has score just less than given score

From a redis sorted set, how do I retrieve the rank of highest value that has a score just less than a given score?

For instance, imagine my sorted set is:

rank value score
1)   'a'   -10
2)   'd'   -4
3)   'c'   0
4)   'b'   2
5)   'e'   10

Specifically, If I'm given the score 12, I want to retrieve rank 5. If I'm given the score 1, I want to retrieve rank 3. If I'm given a score -11, I want to retrieve nothing.

Upvotes: 0

Views: 1080

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 49942

Note #1: rank in a Sorted Set is 0-based

Note #2: you'll have to do two queries, one for finding the element and the other for obtaining its rank.

Example using redis-cli:

127.0.0.1:6379> ZADD z -10 a -4 d 0 c 2 b 10 e
(integer) 5
127.0.0.1:6379> ZREVRANGEBYSCORE z (12 -inf LIMIT 0 1
1) "e"
127.0.0.1:6379> ZRANK z e
(integer) 4
127.0.0.1:6379> ZREVRANGEBYSCORE z (1 -inf LIMIT 0 1
1) "c"
127.0.0.1:6379> ZRANK z c
(integer) 2
127.0.0.1:6379> ZREVRANGEBYSCORE z (-11 -inf LIMIT 0 1
(empty list or set)

Naturally, a Lua script would be ideal for this case, i.e:

$ cat script.lua 
local r=redis.call('ZREVRANGEBYSCORE', KEYS[1], '('..ARGV[1], '-inf', 'LIMIT', 0, 1)
if #r > 0 then
  r=redis.call('ZRANK', KEYS[1], r[1])
end
return r
$ redis-cli --eval script.lua z , 12
(integer) 4
$ redis-cli --eval script.lua z , 1
(integer) 2
$ redis-cli --eval script.lua z , -11
(empty list or set)

Upvotes: 1

Related Questions