Random-access string storage
Treat a Redis string as a byte-addressable sequence and update a region without replacing the entire value.
Redis · Module
Overwrites part of a Redis string from a specified zero-based offset. It pads with zero bytes when necessary and returns the string's resulting length.
SETRANGE replaces bytes in the string stored at a key, beginning at a zero-based offset and continuing for the length of the supplied value. If the key is missing, Redis treats it as an empty string; if the offset extends past the current value, Redis inserts zero-byte padding before writing. The command returns the resulting string length.
SETRANGE key offset value| Name | Type | Description |
|---|---|---|
key | string key | The name of the key. |
offset | integer | The zero-based offset at which to start overwriting. The string is zero-padded if the offset is beyond the current length. |
value | string | The string to write at the offset. |
Integer reply: the length of the string after it was modified by the command.
SET key1 "Hello World"
SETRANGE key1 6 "Redis"
GET key1Writes "Redis" starting at byte offset 6, then reads the resulting string: "Hello Redis".
Treat a Redis string as a byte-addressable sequence and update a region without replacing the entire value.
Store compact per-entity byte values in a large string, using offsets as positions.
Combine with GETRANGE to read and update fixed regions of a string.
SETRANGE uses a zero-based offset and overwrites the existing string for the entire length of the new value. If the write extends beyond the current end, Redis pads the gap with zero bytes and returns the final string length.
Follow-up: What happens when the key does not exist? Redis treats it as an empty string, creates the string, and places the supplied value at the requested offset.
The command's syntax is SETRANGE key offset value. key identifies the string, offset is the zero-based starting position, and value is the string written there.
Follow-up: How should an offset beyond the existing value be interpreted? It causes zero-byte padding before the new value is stored.
The documented complexity is O(1), excluding the time needed to copy the new string in place. When the value being copied is longer, the complexity is O(M), where M is its length.
Follow-up: What storage pattern does Redis documentation associate with SETRANGE and GETRANGE? They can treat strings as linear arrays with O(1) random access.
GETRANGESETGETSETBITGETBIT