To create a simple error handling mechanism in our applications, we can use the Redis EXISTS command to verify the key before executing a query.
Redis SET Key
Let us assume you have a key-value pair as shown below:
OK
We create a new Redis key and value using the SET command in the previous command.
To get the value associated with a specific key, we can use the GET command as shown below:
"myvalue"
This should return the value stored by the key “mykey”.
Redis EXISTS Command
The EXISTS command in Redis allows us to determine if a specified key exists in the database.
For example, to check if the key “mykey” exists in the selected database, we execute the following command:
(integer) 1
The command returns (integer) 1 if the key is found and (integer) 0 if not. The following example is provided:
(integer) 0
Note that you can pass multiple keys as the parameters. An example is provided below:
(integer) 1
The command will take the provided keys and check how many exist within the selected database.
For example, the previous command returns (integer) 1 since only one key exists in the database.
What happens if you specify the same key more than once?
Take the following example commands below:
127.0.0.1:6379> set key2 two
127.0.0.1:6379> set key3 three
We can check the same key multiple times using the following command shown:
(integer) 2
Redis ignores the repeated keys and counts the unique values in this case.
NOTE: The existence of the key is only checked in the currently selected database. For the following example, let us switch to database 2:
OK
127.0.0.1:6379[2]>
Note: the prompt changes to reflect the currently selected database.
In this database, let us create a new key and value pair as shown below:
OK
Switch back to the database at index 0.
OK
127.0.0.1:6379>
If you check the existence of the key “user1”, Redis will return 0.
(integer) 0
The EXISTS command only checks the key in the currently selected database.
Conclusion
This article details how to check if a key exists within the currently selected database within a Redis instance. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.
from https://ift.tt/j2ehr1A
0 Comments