Redis-CLI Get/Set Key Value Pairs: How to Do It? [10 Easy Steps]

Written by

Reviewed by

Last updated: June 14, 2024

Expert verified

SVG Image

TL;DR

Here is how to Redis-CLI get/set key value pairs:

  1. Install Redis with sudo apt install redis-server.
  2. Check that Redis is running with sudo systemctl status redis, then connect to the Redis server using redis-cli.
  3. Set a key-value pair with SET testKey helloWorld and set an expiring key with SETEX tempKey 300 temporary.
  4. Retrieve the values of keys using GET testKey and MGET testKey anotherKey to manage multiple keys.

Keep reading for detailed steps on how to use the Redis-CLI get/set key value pairs in Ubuntu, along with common problems you might encounter.

Ever run into trouble managing data on your Ubuntu system? Redis CLI is a great tool for quickly setting and retrieving key-value pairs, but it can be tricky to get started. Don’t worry, I’m here to help you through it! In this post, I’ll show you how to install Redis, start using it right away, and run basic commands like SET and GET. Plus, I’ll tackle some common issues that might pop up along the way. Whether you’re new to Redis or need a quick refresher, this guide will make sure you’re ready to handle your database tasks with confidence

What Are Key-Value Pairs and How Do They Work?

Key-value pairs are a fundamental concept in data storage and management, especially in databases. They consist of two elements:

  • Key: A unique identifier that acts as a label for the data. Each key is distinct, ensuring that each piece of data can be uniquely identified and accessed.
  • Value: The actual data or information associated with the key. This can be any type of data, such as numbers, text, or more complex data structures.

Key-value pairs are popular because of their simplicity and efficiency. Here’s how they work:

  • Storage: Data is stored as key-value pairs. The key acts as an index, making it easy to find the data.
  • Retrieval: To retrieve data, you use the key to quickly locate the associated value. This process is fast because you don’t have to search through all the data; you simply use the key to jump directly to the value.
  • Updates: Updating data is straightforward. You use the key to find the value you want to change and then update it.

Key-value pairs are widely used in various applications, including databases, configuration files, and caches. Their ability to handle diverse data types and provide rapid access makes them a preferred choice for many developers and systems.

How to Use Redis-CLI Get/Set Key Value Pairs?

To use Redis CLI to set and get key-value pairs, first connect to your Redis server by typing redis-cli in your terminal. To set a key-value pair, use the command SET key value, replacing the key with your desired key and value with your data.

For example, SET mykey myvalue stores myvalue under the key mykey. To retrieve the value, use GET key. For instance, GET mykey will return myvalue” These simple commands allow you to efficiently store and retrieve data using Redis

Follow these detailed steps:

  1. Open a Terminal window.
open terminal
  1. Update your package list with the command: 
sudo apt update

This command updates the list of available packages and their versions.

updating system package list
  1. Now install Redis by executing the command: 
sudo apt install redis-server

This installs the Redis server on your Ubuntu system.

installing redis on ubuntu
  1. Ensure Redis is running by using the command: 
sudo systemctl status redis

If Redis is running properly, you’ll see an output indicating that the service is active. Now, you can start interacting with Redis using the command line interface (CLI).

checking redis service status
  1. Connect to the Redis server by typing and pressing Enter:
redis-cli

You are now interacting with the Redis server directly through your Terminal.

connecting to redis server
  1. Redis CLI set key-value pair using the SET command::
SET testKey helloWorld

This command sets the key testKey with the value helloWorld. Redis will confirm with OK if successful.

setting key value pairs in redis
  1. Redis get value of key using the GET command:
GET testKey

This command retrieves the value associated with testKey. The output will be helloWorld if the key exists.

retrieving the value of key in redis
  1. Redis also allows you to set keys that expire after a given number of seconds using the SETEX command. Set a key that expires after a specified time using SETEX:
SETEX tempKey 300 temporary

This command sets the key tempKey with the value temporary and an expiration time of 300 seconds (5 minutes).

setting a key with expiration
  1. If you need to get key value of multiple keys simultaneously, you can use the MGET command. First, set another key-value pair:
SET anotherKey exampleValue

This sets another key anotherKey with the value exampleValue.

setting another key value
  1. Redis get key value of both testKey and anotherKey together by entering the command:
MGET testKey anotherKey

This command will return a list of values for the keys specified.

retrieving multiple keys

Common Pitfalls and How to Avoid Them

When working with key-value pairs in Redis, you may encounter several common pitfalls. Knowing these issues and understanding how to avoid them can save you time and frustration. Here are five common pitfalls and tips to help you avoid them:

  • 📛 Key Collisions: Using the same key for different data can cause data overwrites. To avoid this, use clear and consistent naming conventions for keys, such as including prefixes or namespaces to differentiate related keys.
  • 🧠 Memory Management: Redis stores data in memory, so it can run out of space if not managed well. Monitor memory usage regularly and set appropriate expiration times for keys to free up space.
  • ⏲️ Expiring Keys: Forgetting to set expiration times for keys that should be temporary can lead to memory bloat. Always set expiration times for temporary data using commands like SETEX or EXPIRE.
  • 📈 Handling Large Datasets: Storing large datasets in Redis can slow down performance. Split large datasets into smaller chunks, and use data structures like hashes, lists, or sets to organize and access data efficiently.
  • ⚖️ Scaling Issues: Redis can face performance issues as the dataset grows. Use Redis clustering and sharding to distribute data across multiple nodes, improving scalability and performance. Regularly monitor and adjust your setup to handle growing data needs.

In a Nutshell

By following this step-by-step guide, you now know how to use Redis CLI to set and get key-value pairs effectively. I’ve covered the basics of connecting to your Redis server using commands like SET and GET, and even setting keys with expiration times. Plus, I’ve explored common pitfalls and offered tips to troubleshoot errors, making sure you can manage your data smoothly and efficiently.

If you’re eager to explore more, I recommend checking out a few more topics to enhance your skills further:

Frequently Asked Questions

What is Redis CLI?

Redis CLI, or Redis Command Line Interface, is a simple, interactive command-line tool that allows you to communicate with a Redis server, manage data stored in Redis, and perform various administrative tasks. It is part of the Redis software package and is primarily used for debugging, testing, and interacting directly with the Redis database in real-time. By running the command redis-cli, you can execute Redis commands to set keys, get values, configure the server, and monitor its performance, among other operations. This tool is essential for developers and administrators to manage Redis databases efficiently.

What is GET Command?

This command is used to retrieve the value associated with a key. If you use the GET command with a key, it returns the value if the key exists; otherwise, it returns nil. For example, GET username would return John if the key username was previously set.

What is SET Command?

This command is used to store data in the form of a key-value pair. When you use the SET command, you specify a key and assign a value to it. If the key already exists, its value is overwritten with the new value. For example, SET username John would create a key named username with the value John.

How can I recover lost keys in Redis if not backed up?

In Redis, if keys are lost and not backed up, recovery is not possible as Redis does not store data permanently by default. To prevent data loss, enable persistence options like AOF (Append Only File) or RDB (Redis Database Backups) which allow recovery from disk.

How do I rename a key in Redis, and what happens if the new key already exists?

To rename a key in Redis, use the RENAME command. If the new key name already exists, the old key is deleted and replaced by the new key. This operation is atomic, ensuring the key is renamed without interruption.

Is there a way to set multiple keys at once in Redis? If so, how?

Yes, you can set multiple keys at once in Redis using the MSET command. This command allows you to specify multiple key-value pairs in a single command, making the process efficient and faster than setting each key individually.

Ojash

Author

Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

Akshat

Reviewer

Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

Share this article
Shareable URL
Prev Post

3 Easy Ways To Set Special Permission in Linux?

Next Post

The Easiest Way to Enable Automatic Updates on Ubuntu

Leave a Reply

Your email address will not be published. Required fields are marked *

Read next