Redis

Redis Check If Key Exists

Redis is a free, open-source in-memory key-value database used in high-performance applications. Redis is highly scalable and provides a collection of tools and extensions as a primary database for non-trivial applications.

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:

$ redis-cli

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:

SET "key” "value"

For example:

127.0.0.1:6379> SET user1 "first_user"

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:

127.0.0.1:6379> SET 0 "First"

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:

GET <key>

For example, to get the value stored in the key user1, you can run the following command:

127.0.0.1:6379> GET user1

"first_user"

In some instances, you may have a key holding the numerical value 0. Take the following example:

127.0.0.1:6379> SET balance 0

OK

In the previous command, we have the key “balance” holding 0. Therefore, if we get the value of the key, we get 0.

127.0.0.1:6379> GET balance

"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:

EXISTS [key]

An example usage is provided below:

127.0.0.1:6379> EXISTS balance

(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:

127.0.0.1:6379> EXISTS user1 balance

(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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list