Redis Sorted Set - Pick one member before and one after a specific score

623 Views Asked by At

I create Redis (v7) Sorted Sets with ZADD. Each set has multiple members. The score I use is a timestamp.

With ZRANGE I'm able to select members with scores between min and max. I want to select - based on one timestamp - one member after the timestamp and one before the timestamp.

Example (score, member) for one key:

(10, A)
(15, B)
(20, C)

I.e. SELECT 17 should give me (15, B) and (20, C).

Looks like Redis has no command to do this. What would be the most efficient way to do that?

1

There are 1 best solutions below

0
for_stack On

You need two commands:

# get the one after the timestamp
zrangebyscore k (17 +inf limit 0 1

# get the one before the timestamp
zrevrangebyscore k (17 -inf limit 0 1

In order to be more efficient and atomic, wrap these two commands into a Lua script.