0
0
RedisHow-ToBeginner · 3 min read

How to Use HKEYS Command in Redis: Syntax and Examples

In Redis, use the HKEYS command to retrieve all the field names (keys) stored in a hash. The command syntax is HKEYS key, where key is the name of the hash. It returns a list of all fields inside that hash.
📐

Syntax

The HKEYS command syntax is simple:

  • HKEYS key: Returns all field names in the hash stored at key.

If the hash does not exist, it returns an empty list.

redis
HKEYS myhash
Output
1) "field1" 2) "field2" 3) "field3"
💻

Example

This example shows how to create a hash and then use HKEYS to get all its fields.

redis
127.0.0.1:6379> HSET myhash field1 "Hello"
(integer) 1
127.0.0.1:6379> HSET myhash field2 "World"
(integer) 1
127.0.0.1:6379> HSET myhash field3 "!"
(integer) 1
127.0.0.1:6379> HKEYS myhash
Output
1) "field1" 2) "field2" 3) "field3"
⚠️

Common Pitfalls

Common mistakes when using HKEYS include:

  • Using HKEYS on a key that is not a hash, which returns an error.
  • Expecting HKEYS to return values instead of field names.
  • Not handling the case when the hash key does not exist, which returns an empty list.
redis
127.0.0.1:6379> SET mystring "value"
OK
127.0.0.1:6379> HKEYS mystring
(error) WRONGTYPE Operation against a key holding the wrong kind of value

-- Correct usage:
127.0.0.1:6379> HKEYS myhash
1) "field1"
2) "field2"
3) "field3"
📊

Quick Reference

HKEYS Command Summary:

CommandDescriptionReturns
HKEYS keyGet all field names in the hash stored at keyArray of field names
HGET key fieldGet value of a specific fieldValue string or nil
HSET key field valueSet field in hash to value1 if new field, 0 if updated
DEL keyDelete the key1 if deleted, 0 if not found

Key Takeaways

Use HKEYS to get all field names from a Redis hash key.
HKEYS returns an empty list if the hash does not exist.
Do not use HKEYS on keys that are not hashes to avoid errors.
HKEYS returns only field names, not their values.
Combine HKEYS with HGET to retrieve values for each field.