Advertisement
Intermediate 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?

Short 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…

Save Redis mock interview
Advertisement
AModel 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.
Example

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.
Likely 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?
Related topics