The Redis HKEYS
command is used to get all the keys in a hash. This is particularly useful when you want to enumerate through all the keys in a hash for various purposes such as data migration, debugging, or analytics.
Let's start with initializing our Redis client:
const redis = require('redis'); const client = redis.createClient(); client.on('connect', function() { console.log('connected'); });
Here's an example of how to use HKEYS
:
client.hmset('hashKey', 'key1', 'value1', 'key2', 'value2', 'key3', 'value3', function(err, reply) { if (err) { console.log(err); } console.log(reply); // returns 'OK' }); client.hkeys('hashKey', function(err, keys) { if (err) { console.log(err); } console.log(keys); // returns ['key1', 'key2', 'key3'] });
In this example, we first create a hash with the key 'hashKey'. We then fetch all the keys from 'hashKey' using HKEYS
. The result is an array of all the keys in the hash.
HKEYS
operation is quick and won't block your server even on large hashes, consider your use case carefully. If your application needs to frequently fetch all keys from very large hashes, it may indicate a need for refactoring your data structures or strategies.HKEYS
command might throw, such as when trying to get keys from a non-existing hash or a key that is not a hash.What if I use HKEYS
on a non-existing hash?
If you use HKEYS
on a non-existing hash, Redis will consider it an empty hash and return an empty list.
What happens if the key exists but is not a hash type in Redis?
An error will be returned because HKEYS
can only be used on hash types.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.