In Redis, it’s possible to set a key only if it doesn’t already exist. As with most things, there’s more than one way to do this.
The SET
Command
We can use the SET
command to do exactly what we want. When we use this command, we need to use the NX
option to specify that the key should be set only if it doesn’t already exist.
Example:
SET user "Homer" NX
Result:
OK
In this case, the key didn’t already exist, and so we got OK
as the result (which means that the key was set).
To test the NX
option, let’s try to set the key to a different value while using the NX
option:
SET user "Marge" NX
Result:
(nil)
The key couldn’t be set because it already exists. In this case we get a result of (nil)
.
Note that the NX
option was introduced in Redis 7.0.0, so if you use an earlier version, try the SETNX
command instead (below).
The SETNX
Command
The SETNX
command does the same thing that the SET
command does when using the NX
option. It specifies that the key should be set only if it doesn’t already exist.
Example:
SETNX spouse "Marge"
Result:
(integer) 1
This command returns an integer reply of 1
when it sets the value successfully (which is what happened in this case).
Now let’s try to set the key to a different value:
SETNX spouse "Marilyn"
Result:
(integer) 0
We get an integer reply of 0
, which means that the key wasn’t set.
We can verify this by checking the key’s value:
GET spouse
Result:
"Marge"
As expected, it’s still the original value.