How to Use XRANGE in Redis: Syntax and Examples
Use the
XRANGE command in Redis to read entries from a stream within a specified ID range. The syntax is XRANGE key start end [COUNT count], where start and end define the range of stream IDs to fetch. This command returns the stream entries in order from start to end.Syntax
The XRANGE command reads entries from a Redis stream between two IDs.
- key: The name of the stream.
- start: The starting ID of the range (inclusive). Use
-for the earliest entry. - end: The ending ID of the range (inclusive). Use
+for the latest entry. - COUNT count (optional): Limits the number of entries returned.
redis
XRANGE key start end [COUNT count]
Example
This example shows how to add entries to a stream and then read a range of entries using XRANGE.
redis
127.0.0.1:6379> XADD mystream * sensor-id 1234 temperature 19.8 "1588151234567-0" 127.0.0.1:6379> XADD mystream * sensor-id 1235 temperature 20.1 "1588151234570-0" 127.0.0.1:6379> XRANGE mystream - + 1) 1) "1588151234567-0" 2) 1) "sensor-id" 2) "1234" 3) "temperature" 4) "19.8" 2) 1) "1588151234570-0" 2) 1) "sensor-id" 2) "1235" 3) "temperature" 4) "20.1"
Output
1) 1) "1588151234567-0"
2) 1) "sensor-id"
2) "1234"
3) "temperature"
4) "19.8"
2) 1) "1588151234570-0"
2) 1) "sensor-id"
2) "1235"
3) "temperature"
4) "20.1"
Common Pitfalls
Common mistakes when using XRANGE include:
- Using incorrect ID formats for
startorend. IDs must be in the formmilliseconds-sequence. - Not using
-or+to specify the full range. - Forgetting that
XRANGEreturns entries in ascending order, so thestartID must be less than or equal to theendID. - Not using
COUNTwhen expecting a limited number of results, which can cause large data returns.
redis
Wrong: XRANGE mystream + - Right: XRANGE mystream - +
Quick Reference
| Parameter | Description |
|---|---|
| key | Name of the stream to read from |
| start | Start ID of the range, use '-' for earliest |
| end | End ID of the range, use '+' for latest |
| COUNT count | Optional limit on number of entries returned |
Key Takeaways
Use
XRANGE key start end to read stream entries between IDs.Use '-' and '+' to specify the full range from earliest to latest entries.
Include
COUNT to limit the number of returned entries.Ensure IDs are in the correct format:
milliseconds-sequence.Remember
XRANGE returns entries in ascending order by ID.