Redis

Using Redis Hash

In Redis, a hash is a primitive data type that represents a mapping between a field and its associated value. Yes, like JSON, but not quite.

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:

127.0.0.1:6379> hset users id 1 first_name "Mary" lastname "Wies" email "[email protected]"

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

127.0.0.1:6379> hmget users first_name

1) "Mary"

If the specified hash does not exist, the command will return nil as shown:

127.0.0.1:6379> HMGET nokey nofield

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:

127.0.0.1:6379> HKEYS users

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:

127.0.0.1:6379> HVALS users

1) "1"

2) "Mary"

3) "Wies"

4) "[email protected]"

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:

127.0.0.1:6379> HGETALL users

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:

127.0.0.1:6379> HDEL users id

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

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