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

5 years 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, For this, we will use Redis HSET, HSETNX, and HMSET commands.

HSET Command

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

Error is returned, if the key exists but value stored at the key is not of a hash datatype. The syntax of the 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 the specified value to its respective field in the hash stored at a specified key, only if a field does not exist in the hash value and if the field already exists, then this operation has no effect. If the key does not exist, then a new key holding a hash value is created before performing the set operation. 

Error is returned, if the key exists but value stored at the key is not of a hash datatype. The syntax of the 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 the key does not exist, then a new key holding a hash value is created before performing the set operation.

Error is returned, if the key exists but value stored at the key is not of a hash datatype. The syntax of the 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.

<- Hash Commands