Redis provides us with a convenient way to set multiple strings at once. Specifically, the MSET
command enables us to set multiple strings in one go.
There’s also the MSETNX
command which does the same thing, but only if none of the keys already exist.
Example
Here’s an example of using the MSET
command to set multiple strings:
MSET firstname "Rob" lastname "Banks" age 28
Result:
OK
This returns OK
which means that all keys were set successfully.
We can use the MGET
command to check their values:
MGET firstname lastname age
Result:
1) "Rob" 2) "Banks" 3) "28"
Overwrite Existing Keys
If one or more keys already exist, MSET
replaces existing values with new values.
For example, we can set one or more of the above keys with new values:
MSET firstname "Rob" lastname "Bery" age 29
Result:
OK
Check the result:
MGET firstname lastname age
Result:
1) "Rob" 2) "Bery" 3) "29"
Don’t Overwrite Existing Keys
Sometimes we might not want to overwrite any keys if they already exist. In such cases, we can use the MSETNX
command. With this command, the operation fails if any of the keys already exist.
For example:
MSETNX user "Chax" age 30
Result:
(integer) 0
In this case we get an integer reply of 0
, which means that nothing was set. That’s because at least one of the keys already exists. In our case, the age
key already exists (because we created it in the earlier examples).
This prevents us from accidentally overwriting something that we shouldn’t.
If we delete the age
key and try again, we’ll be successful:
DEL age
Result:
(integer) 1
An integer reply of 1
means that it was successfully deleted.
Now let’s try running MSETNX
again:
MSETNX user "Chax" age 30
Result:
(integer) 1
This time we get an integer reply of 1
, which means that it was successful.
Let’s check the values:
MGET user age
Result:
1) "Chax" 2) "30"
Setting Timeouts, etc
If we need to set extra attributes for the keys, such as timeouts, we’ll need to use another approach.
Probably the most logical approach is to use the SET
command. This command accepts arguments for things like timeouts and whether or not to overwrite the key if it exists, etc.
The downside is that we can only set one key at a time.
Therefore, we could use the following to set one of the above keys, only if it doesn’t exist:
SET user "Chax" NX EX 60
Result:
(nil)
In this case, nothing was set, because the key already exists. The NX
argument specifies that the key can only be set if it doesn’t already exist. The EX
argument allows us to specify a timeout in seconds.
But as mentioned, if we have multiple keys to set, we would need to run multiple calls to SET
, one for each key we need to set. For example, here’s one for the age
key:
SET age 31 GET KEEPTTL
Result:
"30"
In this case, I didn’t specify NX
, so the key was overwritten with the new value. I also used the GET
argument to return the old value of the key. And I used the KEEPTTL
option to keep any timeouts as they are.
Here’s the new value:
GET age
Result:
"31"