Pagination with Redis Sorted Set

Consider a sorted Redis collection with the following members:

ZADD mySortedSet 11 "A"
ZADD mySortedSet 21 "B"
ZADD mySortedSet 32 "C"
ZADD mySortedSet 46 "D"
ZADD mySortedSet 53 "E"
ZADD mySortedSet 68 "F"
ZADD mySortedSet 72 "G"
ZADD mySortedSet 82 "H" 
ZADD mySortedSet 94 "I"
ZADD mySortedSet 104 "J"
ZADD mySortedSet 113 "K"

If I want to paginate in the reverse order, starting with an arbitrary fragment, I can start with this:

// Returns G, F, E, as expected.
ZREVRANGEBYSCORE mySortedSet 72 (46

Now, knowing only that my upper bound is 46, I can get the previous 3 elements in sets D, C and B without knowing the lower bound:

ZREVRANGEBYSCORE mySortedSet 46 -inf LIMIT 0, 3

My question is: how can I get the following 3 elements in a set, J, I and H in that order, knowing only that the upper bound is 72?

// Good start, returns K, J, I, H
ZREVRANGEBYSCORE mySortedSet +inf (72

// Returns K, J, I, due to the offset of 0.  I don't know what the correct offset is because it from the start of the range, not the end.
ZREVRANGEBYSCORE mySortedSet +inf (72 LIMIT 0, 3

I think what I want is a negative bias, which I think is not supported.

// Would return J, I, H, but actually returns an empty set.
ZREVRANGEBYSCORE mySortedSet +inf (72 LIMIT -1, 3

I can fake it with a range ahead and then flip these elements, but I was looking for a native Redis solution, if one exists.

// Returns H, I, J - the items I want, but reversed.
ZRANGEBYSCORE mySortedSet (72 +inf LIMIT 0, 3

Any ideas?

, , ZRANGE ZREVRANGE, , .

+5
1

, , . , , , 72 46, :

redis 127.0.0.1:6379> ZREVRANGEBYSCORE mySortedSet 72 (46
1) "G"
2) "F"
3) "E"
redis 127.0.0.1:6379> ZREVRANK mySortedSet G
(integer) 4
redis 127.0.0.1:6379> ZREVRANGE mySortedSet 1 3
1) "J"
2) "I"
3) "H"
redis 127.0.0.1:6379> 

O (log (N)) ZREVRANK. , , , ZREVRANGE, .

Redis 2.6rc5, 2.0.

+1

All Articles