Here are a couple of ways to check whether or not a key exists in Redis.
The EXISTS
Command
First up, we can use the EXISTS
command to check for one or more keys. This command returns an integer reply with the number of keys matched.
Here’s an example to demonstrate how the EXISTS
command works:
EXISTS customer
Result:
(integer) 1
In this case we get an integer reply of 1
, which means that the key exists.
We can pass more than one key to the command:
EXISTS customer animals house
Result:
(integer) 2
In this case, I passed three keys. We get an integer reply of 2
, which means that two of those keys exist and one doesn’t.
Note that passing the same key multiple times will result in that key being counted multiple times if it exists. Here’s an example to illustrate what I mean:
EXISTS customer customer customer
Result:
(integer) 3
The KEYS
Command
Another way to check for the existence of a key is to pass the key name to the KEYS
command. This command returns a list of keys that match the given pattern. So if it returns a key with the same name that was passed to it, then the key exists.
The pattern can be the actual name of the key or it can be a broader pattern that encompasses the name of the key but may also match other keys.
Here’s an example that specifies the actual name of the key:
KEYS customer
Result:
1) "customer"
In this case we get the name of the actual key and no more.
Here’s an example of using a broader pattern:
KEYS *name*
Result:
1) "username" 2) "firstname" 3) "lastname" 4) "name" 5) "listname"
This time we get a list of five keys that match the given pattern.