Redis

Redis HGETALL

When working with Redis hashes, you can utilize the HGETALL command to retrieve all the fields and values from a hash.

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:

127.0.0.1:6379> HSET user_info firstname Ruby lastname Rue email ruby@mail.io career "Game Developer."

(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:

127.0.0.1:6379> HMSET user_info country US

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:

127.0.0.1:6379> HGET user_info firstname

"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:

127.0.0.1:6379> HGETALL user_info

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:

127.0.0.1:6379> HGETALL nokey

(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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list