0
0
Redisquery~5 mins

ZRANGEBYLEX for lexicographic queries in Redis

Choose your learning style9 modes available
Introduction
ZRANGEBYLEX helps you get items from a sorted list based on alphabetical order, not numbers.
You want to find all names starting with a certain letter in a list.
You need to get all words between 'apple' and 'banana' alphabetically.
You want to list all items that come after 'cat' but before 'dog' in a dictionary.
You want to filter usernames that start with letters between 'a' and 'm'.
Syntax
Redis
ZRANGEBYLEX key min max [LIMIT offset count]
min and max define the lexicographic range using special characters: '[' means inclusive, '(' means exclusive, '-' means minimum, '+' means maximum.
LIMIT is optional and helps you get a smaller part of the results by skipping some and limiting how many you get.
Examples
Gets all items from 'myset' starting at 'apple' and including 'banana'.
Redis
ZRANGEBYLEX myset [apple [banana
Gets all items from 'myset' after 'apple' but before 'banana', excluding both.
Redis
ZRANGEBYLEX myset (apple (banana
Gets all items from 'myset' in alphabetical order.
Redis
ZRANGEBYLEX myset - +
Gets the first 3 items from 'myset' between 'cat' and 'dog', including both.
Redis
ZRANGEBYLEX myset [cat [dog LIMIT 0 3
Sample Program
We add fruits with score 0 (score is ignored for lex queries). Then we get fruits from 'banana' to 'fig' inclusive, sorted alphabetically.
Redis
127.0.0.1:6379> ZADD fruits 0 apple 0 banana 0 cherry 0 date 0 fig 0 grape
(integer) 6
127.0.0.1:6379> ZRANGEBYLEX fruits [banana [fig
1) "banana"
2) "cherry"
3) "date"
4) "fig"
OutputSuccess
Important Notes
ZRANGEBYLEX only works on sorted sets where all scores are the same or ignored; it sorts by member name alphabetically.
Time complexity is O(log(N)+M) where N is total elements and M is returned elements.
Common mistake: Using ZRANGEBYLEX on sorted sets with different scores expecting numeric order; it sorts by member name, not score.
Use ZRANGEBYLEX when you want alphabetical range queries; use ZRANGE for numeric score ranges.
Summary
ZRANGEBYLEX gets items from a sorted set based on alphabetical order.
Use '[' for inclusive and '(' for exclusive range boundaries.
LIMIT helps control how many results you get and where to start.