A Redis hash is more compact and is designed to take up less space for key-value pairs.
Using this guide, let us explore working with Redis hashes and HMGET command.
Redis Create Hash
To create a hash in Redis, use the HSET command followed by the key name and the field and its corresponding value.
An example is as shown:
(integer) 4
In the example above, we create a new key holding four fields and corresponding values.
NOTE: If a key exists in the database, Redis will replace it with the new information.
The best way to add multiple fields and values to a hash is to use the HMSET command.
Redis Retrieve Value (HMGET)
To get a value from a Redis, we use the HMGET command followed by the hash name and the field you wish to access.
For example, to get the value stored in the hash users and the field first_name, we can do:
1) "Mary"
If the specified hash does not exist, the command will return nil as shown:
1) (nil)
Redis Get Hash Fields
To list all the fields of a hash, use the HKEYS command followed by the name of the hash.
An example is as shown:
1) "id"
2) "first_name"
3) "lastname"
4) "email"
This should return the list of fields in the specified hash.
Redis Get Hash Values
You can also perform the same operation to get the list of values in a hash. Use the HVALS command as:
Redis Get Hash Fields and Values
Suppose you want to get the fields and their corresponding values? In such a case, you can use the HGETALL command:
An example usage is as shown below:
1) "id"
2) "1"
3) "first_name"
4) "Mary"
5) "lastname"
6) "Wies"
7) "email"
8) "[email protected]"
The command will list the field and its value, one after another.
Redis Delete Hash Field
To delete a field from a hash, use the HDEL command followed by the hash name and the field you wish to remove.
Consider the example below:
(integer) 1
The command should return the number of fields removed. If a field is not found in the hash, the command returns 0.
Conclusion
This article discusses Redis hashes and the various commands to manage them. Keep practicing!!