How to Use HLEN Command in Redis to Get Hash Field Count
Use the
HLEN command in Redis to get the number of fields stored in a hash. It returns an integer representing how many key-value pairs the hash contains.Syntax
The HLEN command syntax is simple. You provide the key name of the hash, and Redis returns the count of fields inside that hash.
HLEN key: Returns the number of fields in the hash stored atkey.
redis
HLEN myhash
Example
This example shows how to create a hash, add fields, and then use HLEN to get the number of fields in that hash.
redis
HSET myhash field1 "Hello" HSET myhash field2 "World" HLEN myhash
Output
2
Common Pitfalls
One common mistake is using HLEN on a key that does not exist or is not a hash. In such cases, Redis returns 0 or an error respectively.
Also, remember that HLEN counts fields, not the total size or length of values.
redis
HLEN nonexistingkey # Returns 0 because the key does not exist SET notahash "value" HLEN notahash # Returns an error because the key is not a hash
Output
0
(error) WRONGTYPE Operation against a key holding the wrong kind of value
Quick Reference
| Command | Description |
|---|---|
| HLEN key | Returns the number of fields in the hash stored at key |
| HSET key field value | Sets the value of a field in the hash |
| HGET key field | Gets the value of a field in the hash |
| DEL key | Deletes the key and its hash |
Key Takeaways
HLEN returns the count of fields in a Redis hash key.
If the key does not exist, HLEN returns 0.
Using HLEN on a non-hash key causes an error.
HLEN counts fields, not the size of values.
Use HSET to add fields before using HLEN.