Redis Zrangebylex Command
The Redis Zrangebylex command is used to get members within a specified range in a sorted set by 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: the key name, specifying the sorted set to operate on.minandmax: the boundary values of the lexicographic range. These two values can be negative infinity (-) or positive infinity (+), or specific string values. A string value represents the lexicographic boundary of members in the sorted set.LIMIT offset count: optional parameter, used to limit the number of returned results.offsetmeans skipping how many elements from the front,countmeans returning how many elements.
Command behavior:
- If both the
minIs+orminthe first element after,maxIs-ormaxthe last element before, then return the keykeyall elements in the stored sorted set. - If both the
minandmaxare both specific strings, then return the elements in the sorted set whose lexicographic order is betweenminandmax. - If both the
minIs+orminthe first element after, andmaxis a specific string, then return the elements in the sorted set whose lexicographic order is greater than or equal tomax. - If both the
minis a specific string, andmaxIs-ormaxthe last element before, then return the elements in the sorted set whose lexicographic order is less than or equal tomin.
Available Version
= 2.8.9
Return Value
A list of elements within the specified range.
Example
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 with lexicographic order between a and f:
ZRANGEBYLEX myzset a f
Get all elements with lexicographic order greater than b and less than f:
ZRANGEBYLEX myzset [b (f
Get elements with lexicographic order between a and f, but return only the first 3:
ZRANGEBYLEX myzset a f LIMIT 0 3
Note that the ZRANGEBYLEX command performs range queries by lexicographical order, not by score. This makes it very suitable for scenarios that require retrieving data in alphabetical order.
