In Redis, we can use the STRLEN
command to get the length of a given string value, based on its key.
We can also use the HSTRLEN
command to get the string length of a value stored in a hash.
Example – STRLEN
Suppose we have a key with the following string value:
GET fruit
Result:
"Mangosteen"
We can get the length of that string value like this:
STRLEN fruit
Result:
(integer) 10
In this case we get an integer reply of 10
, which indicates that the string is ten characters long.
Let’s do another key:
GET lastname
Result:
"Banks"
We can get the length of that string value like this:
STRLEN lastname
Result:
(integer) 5
This time the return value is 5
, which means that our string is five characters long.
Example – HSTRLEN
We can also get the length of a string that’s stored in a hash.
Suppose we set the following hash:
HSET customer firstname "Rob" lastname "Banks" age 35
Result:
(integer) 3
We just set three fields in our hash.
Now let’s get the length of the firstname
field:
HSTRLEN customer firstname
Result:
(integer) 3
And the lastname
field:
HSTRLEN customer lastname
Result:
(integer) 5
And the age
field:
HSTRLEN customer age
Result:
(integer) 2