The XRANGE
command in Redis is primarily used to read data from a stream within a specified range. It's useful for processing historical data, log analysis, or any scenario where time-series data is involved and you need to retrieve a specific subset based on a range.
Here's a simple example of how to use the XRANGE
command with Go and the go-redis
library:
package main import ( "fmt" "github.com/go-redis/redis/v8" "context" ) func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, }) ctx := context.Background() result, err := rdb.XRange(ctx, "mystream", "-", "+").Result() if err != nil { panic(err) } for _, message := range result { fmt.Println(message.ID, message.Values) } }
In this example, a new Redis client is created with NewClient
, then we use XRange
on the "mystream" stream from the smallest ("-"
) to the largest ("+"
) ID, effectively reading all messages in the stream. Each message is then printed out.
To read between specific IDs:
res, err := rdb.XRange(ctx, "mystream", "1526985755631-0", "1526999359965-0").Result()
This will fetch entries between the given IDs in the 'mystream' stream.
"-"
and "+"
. Remember that "-" means the smallest ID in the stream and "+" indicates the largest.Q: What is the difference between XREAD
and XRANGE
?
A: While both commands are used to read from streams, XRANGE
reads based on a range of IDs while XREAD
can block and wait for new data and allows reading from multiple streams.
Q: Can I use XRANGE
with count argument in GoLang?
A: Yes, you can use the XRangeN
function provided by the go-redis
library:
res, err := rdb.XRangeN(ctx, "mystream", "-", "+", 10).Result()
This will return only the first 10 messages within the specified range.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.