Q:

How may I get the ceiling score (score and member) from a SortedSet in Redis?

In Redis, I want to get the ceiling score (and member) for a score that is not in the SortedSet.
In Java, there is NavigableSet and we may use E ceiling(E e) in order to return the least element in this set greater than or equal to the given element, or null if there is no such element.
Is there any way to do the same in Redis, maybe using SortedSets or other data structure?
Thanks

A:

You can use ZRANGEBYSCORE with a Lua script. Imagine the following sorted set:
zadd test 1 a
zadd test 2 b
zadd test 4 c

You have 3 elements with scores 1, 2, 4 and you'd like to call ceiling(3). Save the following Lua script as script.lua:
local key = KEYS[1]
local givenScore = tonumber(ARGV[1])
local scores = redis.call("ZRANGEBYSCORE", key, givenScore, "+inf", "withscores", "limit", 0, 1)
if (scores == nil or #scores<2) then
    return nil
end
return tonumber(scores[2])

and call it with:
$ redis-cli eval "$(cat script.lua)" 1 test 3

Here are some sample runs with the above data set:
$ redis-cli eval "$(cat script.lua)" 1 test 2
(integer) 2
$ redis-cli eval "$(cat script.lua)" 1 test 3
(integer) 4
$ redis-cli eval "$(cat script.lua)" 1 test 4
(nil)

