Presence and emptiness checks
Check whether a hash contains any fields without retrieving its contents.
Redis · Module
HLEN returns the number of fields in a Redis hash. It runs in O(1) time and returns 0 when the key does not exist.
HLEN takes the key of a Redis hash and returns how many fields it currently contains. The count is constant-time, and a missing key behaves like an empty hash, so the result is 0; using a key with another data type produces a wrong-type error.
HLEN key| Name | Type | Description |
|---|---|---|
key | Redis key | The name of the key that holds the hash. |
The number of fields in the hash, or 0 when the key does not exist.
HSET user:42 name Ada language Redis
HLEN user:42Creates two fields, then returns their count: 2.
Check whether a hash contains any fields without retrieving its contents.
Track the number of attributes, counters, or members represented by a hash.
HLEN returns the number of fields stored in the hash at the supplied key. Its command complexity is O(1), so the count does not require scanning every field.
Follow-up: What happens when the key is absent? Redis returns 0, treating the missing key as an empty hash.
The syntax is HLEN key. The key identifies the Redis hash whose field count should be returned.
Follow-up: How would you count values rather than fields? Use a command such as HVALS to retrieve the values, but that operation is O(N).
HLEN was introduced in Redis 2.0.0 and returns a long integer containing the number of hash fields. It is categorized as a read, hash, and fast command.
Follow-up: What should a client do if the key contains a string instead of a hash? Handle the WRONGTYPE response and correct the key's data-model usage.
HSETHGETALLHVALS