This tutorial will demonstrate how to use the Redis commands to check if a key exists within a specific Redis database.
Redis Set Key
Before exploring how to check if a key exists, we need to insert the sample data. The simplest method is to use the SET command.
Open the terminal and launch the Redis CLI as follows:
127.0.0.1:6379>
In the Redis command-line interface, we can run the SET command followed by a key and its associated value.
The following syntax is as shown:
For example:
OK
The SET command returns OK if the SET operation is executed successfully. If the command fails, the return value is NIL.
You can also store a numerical value as the key. An example is provided below:
OK
The previous command sets the key 0 with the associated value as the string “First.”
Redis GET Key
After setting a key, you can retrieve the value stored in it using the GET command. The syntax is shown below:
For example, to get the value stored in the key user1, you can run the following command:
"first_user"
In some instances, you may have a key holding the numerical value 0. Take the following example:
OK
In the previous command, we have the key “balance” holding 0. Therefore, if we get the value of the key, we get 0.
"0"
This can be confusing because we are unsure whether the key is missing or holding the value 0. We can fix this by checking if the key exists.
Redis Check If Key Exists
We use the EXISTS command to check if a key exists in the Redis database. The following syntax is as shown:
An example usage is provided below:
(integer) 1
The command returns (integer) 1 if the specified key exists in the database. Otherwise, the command returns (integer) 0.
You can pass multiple keys to the command as shown:
(integer) 2
In this case, the command returns the number of keys found.
Conclusion
This tutorial covers creating a key-value pair in Redis, retrieving a value using the specified key, and checking if a key exists in the database. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.