Redis

Redis Get Value of Key

Redis is an in-memory data structure store. It can be implemented as a database, cache, message broker, streaming engine, etc. In action, it’s a key-value database with persistence support. Redis is a high-performance solution with incredible flexibility and scalability.

In this guide, we will explore how to store and fetch data in Redis.

Prerequisites

To perform the steps demonstrated, you will need the following components:

The default configuration of Redis is designed with offline servers in mind. Regardless, you should deploy Redis with proper security configurations to avoid breaches.

Creating a key-value pair

In Redis, a key is necessary to denote a particular data point. The command structure is simple.

The first step is to declare a key-value pair to Redis. This is done using the SET command.

1
$ SET <key> <value> <options>

The following command will create a simple key-value pair:

1
$ SET practice "the quick brown fox"

You can verify if the key is successfully registered in the Redis database using the EXISTS command:

1
$ EXISTS practice

In this example, we created a key with a string value. However, Redis supports various data types, for example, lists, sets, hashes, etc.

Retrieving a value

There are multiple ways we can retrieve the value of a key depending on the data type of the key.

First, we need to check the data type. To check the data type, Redis comes with the TYPE command:

1
$ TYPE <key>

Strings

The most common method of key-value retrieval is using the GET command. It returns the value of the key in string format:

1
$ GET <key>

Hashes

If the data type is hash, then use the HGETALL command:

1
$ HGETALL <key>

Lists

To retrieve a “list” key, use the LRANGE command:

1
$ LRANGE <key> <start_position> <end_position>

Sets

To retrieve a “set” key, Redis comes with the SMEMBERS command:

1
$ SMEMBERS <key>

Zsets

For a “zset” key, use the ZRANGE command:

1
$ ZRANGE <key> 0 -1 withscores

Final Thoughts

This guide demonstrates how to retrieve the value of a key in Redis. There are various commands available to retrieve their values depending on the key type. While the most common method is using GET (retrieves string value), there are other tools like HGETALL (retrieves hash), LRANGE (retrieves list), etc.

Interested in learning more about Redis? The Redis sub-category contains numerous guides on various aspects of Redis. Learn more about SLOWLOG, SADD, and MSET commands in Redis.

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.