In Redis, the GETRANGE
command allows us to get part of a string at a given key, starting and ending at the specified offsets.
The GETRANGE
command replaced the SUBSTR
command, which basically does the same thing. The SUBSTR
command is now considered deprecated (as of Redis 2.0.0).
Syntax
The syntax for GETRANGE
goes like this:
GETRANGE key start end
Example
Suppose we set a key to the following value:
SET band "Avenged Sevenfold"
Result:
OK
And we confirm that it holds that value:
GET band
Result:
"Avenged Sevenfold"
Let’s now use GETRANGE
to get part of that value:
GETRANGE band 8 12
Result:
"Seven"
Here, we returned a substring starting at position 8 and ending at position 12.
Negative Offsets
It’s possible to use negative offsets. When doing this, it starts from the end of the string:
GETRANGE band -8 12
Result:
"even"
Note that the second offset value (the end position) specifies the actual position of the end of the string (not the length of the string). To further illustrate this, here’s what happens when the second value is lower than the starting position:
GETRANGE band -8 7
Result:
""
Bear in mind that the second offset value can also be a negative value:
GETRANGE band -8 -5
Result:
"even"
In this case it counts back from the end of the string (just like the starting value did).
When the Offset is Larger than the Original String
The function limits the resulting range to the actual length of the string.
So here’s an example of what happens when the offset values represent a longer string than the original value:
GETRANGE band 8 30
Result:
"Sevenfold"
And here’s what happens when the starting position is outside of the string:
GETRANGE band 20 30
Result:
""
Non Existent Keys
Specifying a non-existent key results in the empty string:
GETRANGE artist 10 12
Result:
""
Wrong Number of Arguments
Specifying no arguments or the wrong number of arguments results in an error:
GETRANGE band 8
Result:
(error) ERR wrong number of arguments for 'getrange' command