How to Use ZRANGE in Redis: Syntax and Examples
Use the
ZRANGE command in Redis to get elements from a sorted set by specifying the key and the start and stop indexes. You can also include the WITHSCORES option to get the scores along with the elements.Syntax
The basic syntax of ZRANGE is:
ZRANGE key start stop [WITHSCORES]
key: The name of the sorted set.
start and stop: The zero-based indexes to specify the range of elements to retrieve. Use 0 for the first element and -1 for the last element.
WITHSCORES (optional): Returns the scores of the elements along with the elements themselves.
redis
ZRANGE myset 0 -1 WITHSCORES
Example
This example shows how to add elements to a sorted set and then retrieve all elements with their scores using ZRANGE.
redis
127.0.0.1:6379> ZADD myset 10 "apple" 20 "banana" 15 "cherry" (integer) 3 127.0.0.1:6379> ZRANGE myset 0 -1 WITHSCORES 1) "apple" 2) "10" 3) "cherry" 4) "15" 5) "banana" 6) "20"
Output
1) "apple"
2) "10"
3) "cherry"
4) "15"
5) "banana"
6) "20"
Common Pitfalls
Common mistakes when using ZRANGE include:
- Using indexes that are out of range, which returns an empty list instead of an error.
- Forgetting that indexes are zero-based, so the first element is at index 0.
- Not using
WITHSCORESwhen you want to see the scores, resulting in only elements being returned. - Confusing
ZRANGEwithZREVRANGE, which returns elements in reverse order.
redis
Wrong: ZRANGE myset 1 3 Right: ZRANGE myset 1 3 WITHSCORES
Quick Reference
| Option | Description |
|---|---|
| key | Name of the sorted set |
| start | Start index (0-based) |
| stop | Stop index (0-based, inclusive) |
| WITHSCORES | Optional, returns scores with elements |
Key Takeaways
ZRANGE retrieves elements from a sorted set by index range, starting at zero.
Use WITHSCORES to get both elements and their scores in the output.
Indexes can be negative to count from the end, with -1 as the last element.
ZRANGE returns elements in ascending order by score.
Check index bounds to avoid empty results when expecting data.