The Redis HLEN
command returns the number of fields in the hash stored at the specified key.
Syntax
The syntax goes like this:
HLEN key
So all we do is pass the name of the key to the command.
Example
Suppose we set the following hash:
HSET customer firstname "Rob" lastname "Banks" age 37
Result:
(integer) 3
We just set a hash with three fields.
We can use HLEN
to get the number fields in that hash:
HLEN customer
Result:
(integer) 3
The result is an integer reply of the number fields in the hash. In this case, there are three fields in the hash and so 3
is returned.
Let’s add another field to our hash:
HSET customer height 176
Result:
(integer) 1
One field was added.
Now let’s run HLEN
again:
HLEN customer
Result:
(integer) 4
Now it returns 4
as expected.
Non-Existent Keys
Running the command against a key that doesn’t exist results in 0
being returned:
HLEN nonexistentkey
Result:
(integer) 0
Passing the Wrong Number of Arguments
Passing the wrong number of arguments results in an error:
HLEN customer lastname
Result:
(error) ERR wrong number of arguments for 'hlen' command