Redis

Redis HMSET

When building a non-trivial application with Redis, you will find one way or another using a hash type. A hash is a Redis primitive type that allows you to store field and value mapping.

Hence, it is essential to understand the commands that you can use to work with hash types in Redis.

Redis Create Hash

To create a hash in Redis, use the HSET command. The command takes the key name, a field, and value as the parameters.

The syntax is as shown:

HSET key field value

An example is as shown below:

127.0.0.1:6379[15]> HSET user_info firstname "Michael"
(integer) 1

In the example above, we create a new hash type called user_info that holds the field firstname and value “Michael.”

Redis HMSET Command

Redis also has the HMSET command that performs the same operation as HSET command. In addition, the command will overwrite the key with the new values if the key already exists.

NOTE: The Redis version 4.0.0 command is considered deprecated. We prefer that you use HSET with multiple field-value pairs instead.

Source: Redis Official

The example below shows how to use the HMSET command.

127.0.0.1:6379[15]> HMSET new_hash field1 value1
OK

Redis Get Hash

You can get the value associated with a specified hash field using the HGET command as shown:

127.0.0.1:6379[15]> HGET user_info firstname
"Michael"

To get the values of multiple fields, use the HMGET command as shown:

HMGET user_info firstname lastname

You can also get all the fields and associated values using the HGETALL command as shown:

127.0.0.1:6379[15]> HGETALL user_info
1) "firstname"
2) "Michael"

The command should return the hash field and its mapped value.

Conclusion

Understading Redis HMSET command helps to better use hash types in Redis. By following the given guide and easy tutorial, readers should be able to build a non-trivial application with Redis using this hash-type.

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