Redis SUBSTR Equivalent

Many SQL databases have a SUBSTR() or equivalent function that returns a substring from a specified string.

Redis has a SUBSTR command, but it was deprecated in Redis 2.0.0.

However, Redis also has the GETRANGE command, that basically does the same thing. Basically, anything that was possible with the Redis SUBSTR command, is now possible with the GETRANGE command.

And the GETRANGE command does basically the same thing that most of the SUBSTR() and SUBSTRING() functions do in the SQL world – gets a substring from a string.

Example

Here’s a string:

GET animal

Result:

"Bandicoot"

We can use GETRANGE to return a substring from that string:

GETRANGE animal 1 4

Result:

"andi"

The count starts at zero, so 1 starts at the second character. In this case we specified 4 for the end of the substring.

Here it is with different offsets:

GETRANGE animal 3 6

Result:

"dico"

We can also use negative offsets:

GETRANGE animal -4 -1

Result:

"coot"

When using a negative offset, it counts back from the end of the string.