How to set multiple string values in redis – Redis MSET | MSETNX

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to set multiple string values at their respective keys in redis datastore, by using redis MSET, and MSETNX commands.

MSET Command

The MSET command is used to set multiple string values to their respective specified key. If any of the specified key already exist, then it’s value will be overwritten irrespective of its type and any previous expiration time associated with the key will also be removed. MSET command is atomic by nature, so all the specified keys are set at once and this command can’t be fail. The syntax of redis MSET command is as follows :-

Syntax :-

redis host:post> MSET <keyname-1> <value-1> <keyname-2> <value-2> <keyname-3> <value-3>

Output :-

- (string) reply OK, representing a successful operation.

Example :-

Redis MSET

MSETNX Command

The MSETNX command is used to set multiple string values to their respective specified key. If any of the specified key already exist, then operation will be failed and none of the specified keys will be set. MSETNX command is atomic by nature, so all the specified keys are set at once and It is not possible for the clients to see that some of the keys are updated while others are not. The syntax of redis MSETNX command is as follows :-

Syntax :-

redis host:post> MSETNX <keyname-1> <value-1> <keyname-2> <value-2> <keyname-3> <value-3>

Output :-

- 1, if operation is successful and all the string values are set.
- 0, if operation is failed (at least one key already exist) and no string value is set.

Example :-

Redis MSETNX

References :-

  1. MSET Command Docs
  2. MSETNX Command Docs

That’s all for how to set multiple string values at their respective keys in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.

<- String Commands