Redis

Redis Get Key

Redis is a key-value database or data store that utilizes the concept of key and value to store data. Unlike relational databases, keys in Redis must be unique and serve as unique identifiers for the value they hold.

Redis uses simple commands to perform operations using the Redis CLI utility. In this tutorial, you will learn how to fetch the keys in Redis databases.

Setting a Key/Value

Before we get to retrieving keys and the values associated with them, let us learn how to create them.

To create a key and its associated value, use the SET command in the Redis CLI followed by the value.

For example:

SET username "user101"

The “username” acts as a key to the specified value in the example above.

In the example above, we created a key and set an associated value. What if we want to store another username without creating a new key?

To do this, we can use the namespace notation. For example:

SET username:2 "user102"
SET username:3 "user103"

Getting the Key

To get the value stored in a key, you can use the GET command followed by the name of the key.

For example:

GET username
"user101"

The above command tells Redis to fetch the value stored in the specified key.

We can use the GET command followed by the unique value as:

GET username:3
"user103"

Fetching all Keys

Suppose we want to view all the keys stored in the database? To do this, we can use the KEY command followed by a pattern to match.

We can pass the pattern as an asterisk to fetch all the keys. For example, consider the following database containing all the states and their code.

To fetch all the keys, we can do:

KEYS *

The resulting value is as shown:

Although fetching all the keys in the data store can be helpful, it is not recommended to run the command in production or on a large dataset.

Conclusion

In this guide, we discussed how to use the GET command in Redis. You can fetch the values stored in a specified key using this command.

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