0
0
Redisquery~5 mins

XRANGE and XREVRANGE in Redis

Choose your learning style9 modes available
Introduction
XRANGE and XREVRANGE help you read messages from a Redis stream in order, either from oldest to newest or newest to oldest.
You want to see all messages sent to a chat app in the order they arrived.
You need to get the latest updates from a sensor stream starting from the newest.
You want to process events from a stream starting from the oldest event.
You want to review recent logs in reverse order to find the latest errors quickly.
Syntax
Redis
XRANGE key start end [COUNT count]
XREVRANGE key end start [COUNT count]
XRANGE returns stream entries from the start ID to the end ID in ascending order.
XREVRANGE returns stream entries from the end ID to the start ID in descending order.
Examples
Get all entries from the stream 'mystream' from the oldest (-) to the newest (+).
Redis
XRANGE mystream - +
Get up to 5 entries from 'mystream' between two specific IDs.
Redis
XRANGE mystream 1609459200000-0 1609459300000-0 COUNT 5
Get all entries from 'mystream' from newest (+) to oldest (-).
Redis
XREVRANGE mystream + -
Get up to 3 entries in reverse order between two IDs.
Redis
XREVRANGE mystream 1609459300000-0 1609459200000-0 COUNT 3
Sample Program
First, we add two entries to 'mystream'. Then, XRANGE reads all entries from oldest to newest. Finally, XREVRANGE reads the newest entry only.
Redis
XADD mystream * sensor_id 1 temperature 22.5
XADD mystream * sensor_id 2 temperature 23.0
XRANGE mystream - +
XREVRANGE mystream + - COUNT 1
OutputSuccess
Important Notes
The IDs in streams are usually timestamps followed by a sequence number.
Use '-' to mean the smallest ID and '+' to mean the largest ID in XRANGE and XREVRANGE.
COUNT limits how many entries you get back, which helps when streams are very long.
Summary
XRANGE reads stream entries from oldest to newest.
XREVRANGE reads stream entries from newest to oldest.
Both commands can limit results with COUNT and specify ID ranges.