This command will return the field and its corresponding value from the Redis hash. Let us take a look at a few examples.
Creating a Redis Hash
Before using the HGETALL command, create a new hash holding sample information.
To add a new hash in Redis, use the HSET or HMSET commands to set single or multiple field-value pairs.
Take the example below:
(integer) 4
In the command example above, we use the HSET command to set a set of fields and their values in a hash.
We can also do the same with the HMSET command:
OK
Redis Retrieve Fields and Values (HGET & HGETALL)
If you want to retrieve a field and its corresponding value, you can use the HGET command.
This command takes the key name of the target hash and the field you wish to access. An example usage is illustrated below:
"Ruby"
This should return the value of the field if it exists. Otherwise, Redis will return (nil).
In some instances, you may need to get all the fields and corresponding values from a hash. For that, you can use the HGETALL command.
This command takes the name of the hash as the argument and returns all the fields and values sequentially.
Take the example usage shown below:
1) "firstname"
2) "Ruby"
3) "lastname"
4) "Rue"
5) "email"
6) "[email protected]"
7) "career"
8) "Game Developer"
9) "country"
10) "US"
We fetch all the fields and values from the user_info hash in the command above. Keep in mind that each field is accompanied by its value immediately after.
If you attempt to access a non-existing hash, Redis will return an empty hash. For example:
(empty array)
Here, Redis returns an empty array as the hash does not exist.
Conclusion
This short article discusses using various Redis commands to manage hash data types in your Redis server.