How to Use GETRANGE Command in Redis for Substring Extraction
Use the
GETRANGE command in Redis to extract a substring from a string value stored at a key by specifying the start and end indexes. The syntax is GETRANGE key start end, where start and end are zero-based indexes and can be negative to count from the end.Syntax
The GETRANGE command extracts a substring from the string stored at the given key.
- key: The name of the string key.
- start: The starting index (0-based). Use negative numbers to start from the end (-1 is last character).
- end: The ending index (inclusive). Negative indexes count from the end.
The substring includes characters from start to end inclusive.
redis
GETRANGE key start end
Example
This example shows how to store a string and then extract parts of it using GETRANGE.
redis
SET greeting "Hello, Redis!" GETRANGE greeting 0 4 GETRANGE greeting 7 -2
Output
"OK"
"Hello"
"Redis"
Common Pitfalls
Common mistakes when using GETRANGE include:
- Using indexes that are out of range: Redis will return an empty string if
startis greater than the string length. - Confusing inclusive end index: The
endindex is inclusive, soGETRANGE key 0 4returns 5 characters. - Not handling negative indexes properly: Negative indexes count from the end, so
-1is the last character.
redis
/* Wrong: expecting 5 characters but end index is 3 (inclusive) */ GETRANGE greeting 0 3 /* Right: to get 5 characters, use end index 4 */ GETRANGE greeting 0 4
Output
"Hell"
"Hello"
Quick Reference
| Parameter | Description |
|---|---|
| key | The string key to read from |
| start | Start index (0-based, negative counts from end) |
| end | End index inclusive (0-based, negative counts from end) |
Key Takeaways
GETRANGE extracts a substring from a string stored at a key using start and end indexes.
Indexes are zero-based and the end index is inclusive.
Negative indexes count from the end of the string.
Out-of-range indexes return empty strings without errors.
Remember to handle inclusive end index to get the expected substring length.