Question: What is the performance of the HKEYS command in Redis?

Answer

HKEYS is a command in Redis that returns all the keys in a hash. It takes the name of the hash as an argument and provides a list of all keys.

The performance of the HKEYS command depends on the size of the hash. In terms of time complexity, it has O(N) where N is the size of the hash. This means that the larger the hash, the more time it will take for this operation.

It's important to note that in a production environment, if you have a particularly large hash, using HKEYS could potentially block your Redis instance while it processes, which could impact performance. If consistent high performance is crucial, consider alternative ways to manage and access your data.

For example, if you frequently need to retrieve all keys from a hash, but the hash is too big, it might be better to keep track of these keys in a separate Set data structure. Here's a Python code sample showing how you can do this:

import redis r = redis.Redis(host='localhost', port=6379, db=0) # Add value to Hash and Set def add_to_hash_and_set(hash_name, key, value): r.hset(hash_name, key, value) r.sadd(f"{hash_name}-keys", key) # Get all keys from the Set def get_all_keys(set_name): return r.smembers(set_name) # Usage: add_to_hash_and_set("my_hash", "key1", "value1") keys = get_all_keys("my_hash-keys")

This way, every time you add a key-value pair to the hash, you also add the key into a set. The SMEMBERS command also has an O(N) time complexity, but since the Set only stores unique keys (which are usually less data compared to key-value pairs in a hash), it would generally perform faster than HKEYS for large hashes.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.