Back to results for “Map”
Redis › Strings & Bitmaps in Redis

How do you use the SETRANGE and GETRANGE commands to work with a specific portion of a Redis string without affecting or retrieving the rest of it?

Intermediate

Answer

SETRANGE lets you overwrite a specific portion of a string starting at a given offset with new content, and GETRANGE lets you retrieve just a specific substring based on a starting and ending position, both letting you work efficiently with just a portion of a potentially large string value.
SET mystring 'Hello World'
SETRANGE mystring 6 'Redis'
GETRANGE mystring 0 4
Real-world example A logging system that stores fixed format binary data as a string uses SETRANGE to efficiently update just a specific field within that structure, without needing to retrieve, modify, and rewrite the entire value.

Common follow-ups: What happens if SETRANGE is used with an offset beyond the current length of the string?;How efficient is GETRANGE compared to retrieving the entire string and processing it in the application?