DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on • Updated on

Redis Hash Commands

What are Hashes?

Hashes are maps between the string field and the string values. You can also relate it as an object in programming.

In Redis, HASHes can store up to 4 billion field-value pairs.

Set Multiple Field Value in Redis Hash

HMSET in Redis is used to set multiple field-value pairs.

hmset key field value [field value ...]
Enter fullscreen mode Exit fullscreen mode

Redis HMSET

$ 127.0.0.1:6379> hmset student:1 name "Divyanshu Shekhar" rollNo   17 class 10
  OK
Enter fullscreen mode Exit fullscreen mode

Set Field in Hash

Redis HSET is used to set a Field in a pre-existing Redis Hash.

HSET Key Field Value
Enter fullscreen mode Exit fullscreen mode

Redis HSET

$ 127.0.0.1:6379> hset student:1 subject "CS"
  (integer) 1
$ 127.0.0.1:6379> hgetall student:1
  1) "name"
  2) "Divyanshu Shekhar"
  3) "class"
  4) "10"
  5) "subject"
  6) "CS"
Enter fullscreen mode Exit fullscreen mode

Set Field if it doesn’t exist – Redis HSETNX

Redis HSETNX is used to first check if the field exists in the Hash. If the key doesn’t exist then it adds the field in the Hash else drops it.

HSETNX Key Field Value
Enter fullscreen mode Exit fullscreen mode

Redis HSETNX

$ 127.0.0.1:6379> hsetnx student:1 marks 99
  (integer) 1
$ 127.0.0.1:6379> hgetall student:1
  1) "name"
  2) "Divyanshu Shekhar"
  3) "marks"
  4) "99"
Enter fullscreen mode Exit fullscreen mode

Learn more Redis Hash Commands from the original Post.

Also learn how to integrate Redis with Python the blog post: Use Redis with Python: The Power of In-Memory Database.

Find More Blogs on Redis.

Top comments (0)