Redis HSTRLEN Command

The Redis HSTRLEN command allows us to get the length of a value that’s stored in a hash. It returns the string length of the value associated with the specified field at the hash stored in the specified key.

Syntax

The syntax goes like this:

HSTRLEN key field

Example

Suppose we create a key like this:

HSET customer firstname "Ben" lastname "Jamison"

We can use the HSTRLEN command to get the length of one of those fields:

HSTRLEN customer firstname

Result:

(integer) 3

We get an integer reply of 3, which tells us that the firstname field’s value has a string length of three.

Let’s do the the other field:

HSTRLEN customer lastname

Result:

(integer) 7

The value stored in the lastname field has a string length of seven.

Non-Existent Fields

If the field doesn’t exist in the hash, 0 is returned:

HSTRLEN customer height

Result:

(integer) 0

Non-Existent Keys

We also get 0 if the key doesn’t exist:

HSTRLEN nonexistentkey lastname

Result:

(integer) 0

Wrong Key Type

If the key exists, but it doesn’t contain a hash, we get an error:

HSTRLEN color rgb

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

Passing the Wrong Number of Arguments

Passing the wrong number of arguments results in an error

Here’s what happens when I pass too few arguments:

HSTRLEN player

Result:

(error) ERR wrong number of arguments for 'hstrlen' command

And we get the same error when there are too many arguments:

HSTRLEN customer height weight

Result:

(error) ERR wrong number of arguments for 'hstrlen' command