Redis Zrangebylex Command
The Redis Zrangebylex command is used to get members within a specified range in a sorted set in lexicographical order. This command is mainly used for sorted sets whose members are strings.
Syntax
The basic syntax of the redis Zrange command is as follows:
ZRANGEBYLEX key min max [LIMIT offset count]
key: Key name, specifies the sorted set to operate on.minandmax: Boundary values of the lexicographical range. These two values can be negative infinity (-) or positive infinity (+), or they can be specific string values. A string value represents the lexicographical boundary of members in the sorted set.LIMIT offset count: Optional parameters, used to limit the number of returned results.offsetIndicates how many elements to skip from the front,countIndicates how many elements to return.
Command behavior:
- If
minYes+orminthe first element after,maxYes-ormaxthe last element before, then return the keykeyall elements in the stored sorted set. - If
minandmaxare both specific strings, then return the lexicographical order in the sorted set betweenminandmaxall elements between. - If
minYes+orminthe first element after, andmaxis a specific string, then return the lexicographical order in the sorted set that is greater than or equal tomaxall elements. - If
minis a specific string, andmaxYes-ormaxthe last element before, then return the lexicographical order in the sorted set that is less than or equal tominall elements.
Available Versions
>= 2.8.9
Return Value
List of elements within the specified range.
Examples
redis 127.0.0.1:6379> ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g (integer) 7 redis 127.0.0.1:6379> ZRANGEBYLEX myzset - [c 1) "a" 2) "b" 3) "c" redis 127.0.0.1:6379> ZRANGEBYLEX myzset - (c 1) "a" 2) "b" redis 127.0.0.1:6379> ZRANGEBYLEX myzset [aaa (g 1) "b" 2) "c" 3) "d" 4) "e" 5) "f" redis>
Suppose we have a sorted set myzset containing the following elements:
ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g
Get all elements whose lexicographical order is between a and f:
ZRANGEBYLEX myzset a f
Get all elements whose lexicographical order is greater than b and less than f:
ZRANGEBYLEX myzset [b (f
Get elements whose lexicographical order is between a and f, but only return the first 3:
ZRANGEBYLEX myzset a f LIMIT 0 3
Please note that the ZRANGEBYLEX command performs range queries by lexicographical order, not by score. This makes it very suitable for scenarios where data needs to be retrieved in alphabetical order.
Other extensions
