Redis HSET | HSETNX | HMSET – How to set a value to the field in the hash value in redis

3 weeks ago Lalit Bhagtani 0

In this tutorial, we will learn about how to set a value to its respective field in the hash value stored at a key, by using redis HSET, HSETNX and HMSET command.

HSET Command :-

This command is used to set specified value to its respective field in the hash stored at a specified key. If field already exists, then it’s value will be overwritten. If key does not exist, then a new key holding a hash value is created before performing the set operation.

Error is returned, if key exist but value stored at the key is not of hash datatype. The syntax of redis HSET command is as follows :-

Syntax :-

redis host:post> HSET <keyname> <field> <value>

Output :-

- 1 (integer) reply, if a field is new in the hash and value was set.
- 0 (integer) reply, if a field already exists in the hash and value was overwritten.
- Error, if key exist and value stored at the key is not a hash.

Example :-

Redis HSET

HSETNX Command :-

This command is used to set specified value to its respective field in the hash stored at a specified key, only if field does not exist in the hash value and if field already exists, then this operation has no effect. If key does not exist, then a new key holding a hash value is created before performing the set operation. 

Error is returned, if key exist but value stored at the key is not of hash datatype. The syntax of redis HSETNX command is as follows :-

Syntax :-

redis host:post> HSETNX <keyname> <field> <value>

Output :-

- 1 (integer) reply, if a field is new in the hash and value was set.
- 0 (integer) reply, if a field already exists in the hash and no operation was performed.
- Error, if key exist and value stored at the key is not a hash.

Example :-

Redis HSETNX

HMSET Command :-

This command is used to sets specified values to their respective fields ( multiple field/value pair ) in the hash stored at a specified key. If any of the specified fields already exists, then it’s value will be overwritten. If key does not exist, then a new key holding a hash value is created before performing the set operation.

Error is returned, if key exist but value stored at the key is not of hash datatype. The syntax of redis HMSET command is as follows :-

Syntax :-

redis host:post> HMSET <keyname> <field> <value> [ <field> <value> ]

Output :-

- (simple string) reply, OK.
- Error, if key exist and value stored at the key is not a hash.

Example :-

Redis HMSET

References :-

  1. HSET Command Docs
  2. HSETNX Command Docs
  3. HMSET Command Docs

That’s all for how to set a value to its respective field in the hash value stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.