0
0
Redisquery~5 mins

GETRANGE and SETRANGE in Redis

Choose your learning style9 modes available
Introduction

GETRANGE and SETRANGE let you read or change parts of a text stored in Redis without touching the whole text.

You want to read a small part of a long message stored in Redis.
You need to update just a few characters inside a stored string without replacing it all.
You want to check a substring inside a stored value quickly.
You want to save bandwidth by only sending or changing parts of a string.
You want to fix a typo inside a stored string without rewriting the entire string.
Syntax
Redis
GETRANGE key start end
SETRANGE key offset value

GETRANGE returns the substring from start to end (inclusive).

SETRANGE overwrites part of the string starting at offset with value. If the string is shorter, it is extended with zero-bytes.

Examples
Gets the first 5 characters (positions 0 to 4) of the string stored at mykey.
Redis
GETRANGE mykey 0 4
Replaces the string starting at position 6 with "world" inside the value stored at mykey.
Redis
SETRANGE mykey 6 "world"
Gets the last 5 characters of the string stored at mykey. Negative indexes count from the end.
Redis
GETRANGE mykey -5 -1
Sample Program

This example first sets the string "Hello Redis!" to mykey. Then it gets the first 5 characters, which is "Hello". Next, it replaces the substring starting at position 6 with "World", changing the string to "Hello World!". Finally, it gets the entire updated string.

Redis
SET mykey "Hello Redis!"
GETRANGE mykey 0 4
SETRANGE mykey 6 "World"
GETRANGE mykey 0 -1
OutputSuccess
Important Notes

Indexes in GETRANGE are inclusive and zero-based.

SETRANGE returns the length of the string after the change.

If SETRANGE extends the string, the new bytes between old end and offset are zero-bytes (\x00).

Summary

GETRANGE reads a part of a string by specifying start and end positions.

SETRANGE replaces part of a string starting at a given offset with new text.

Both commands help work with substrings without rewriting the whole string.