How to Get All Keys in Redis Using Command Line Interface? [2 Best Methods]

Written by

Reviewed by

Last updated: May 10, 2024

Expert verified

SVG Image

TL;DR

Here is how to get all keys in Redis using CLI:

  1. Connect to Redis using redis-cli, then use the KEYS * command to retrieve all keys or specific patterns like user* for quick debugging or development checks.
  2. Use the SCAN command for a non-blocking, cursor-based iteration over the key space, suitable for large datasets, it requires multiple calls to retrieve all keys and allows adjusting retrieval volume with the COUNT option for efficiency.

Read the guide below to find out how to get all keys in Redis CLI on Ubuntu and the common problems that can happen.


If you’re trying to manage Redis keys using the command line, it can feel a bit tricky, especially with a large database or unexpected issues. In this guide, I’ll show you how to effectively use the KEYS and SCAN commands so you can easily get all keys in Redis or find specific ones. Whether you’re working in a small test environment or managing keys in a busy production setting, this guide will help streamline your process. I’ll walk through each command step-by-step, covering everything from initiating a connection to handling the output.

What are Keys in Redis?

Keys in Redis are unique identifiers that help you store, retrieve, and manage various types of data, such as strings, lists, sets, and hashes. Each key is paired with a value and is distinct within a Redis database. This unique setup allows for quick data operations and retrieval.

Redis keys can also have an expiry time, known as Time to Live (TTL). This feature lets you set a duration after which the key automatically deletes itself, making it useful for temporary data storage like session information or cache management. This ensures that the database uses memory efficiently by removing outdated or unnecessary data automatically.

How to Get All Keys in Redis?

To get all keys in Redis, first connect to the Redis server by typing redis-cli. Once connected, use the KEYS * command to display all keys stored in Redis. This command will return a list of all keys in the current database. Note that using KEYS * can have a significant performance impact on large databases, so in production environments, it’s recommended to use SCAN instead for iterative scanning.

That was the quick answer. Here is the detailed step-by-step guide for each method to get all keys in Redis CLI:

1. KEYS Command

The KEYS command in Redis is used to retrieve all the keys matching a specified pattern. This command is straightforward and useful for debugging or when you need a quick glance at what keys are in your database during the development phases. Follow these steps:

  1. Open your Terminal on Ubuntu and connect to Redis by typing the command:
redis-cli

It will connect you to your Redis server via the command line interface.

connecting to redis
  1. To list all keys in your Redis database, execute the command:
KEYS *

This command will return a list of all keys. 

listing all keys in redis database
  1. If you are looking for keys that match a specific pattern, replace * with your pattern, such as user* for all keys that start with user.
listing keys with specific pattern in redis

2. SCAN Command

The SCAN command is a cursor-based iterator that allows you to iterate over the key space incrementally. This command is designed to provide a non-blocking way to scan through keys, making it suitable for use even in production environments with large datasets. Here is the step-by-step guide:

  1. Start by accessing your Redis CLI on your Ubuntu system.
  2. Initiates the scan operation from the beginning of the database.
127.0.0.1:6379> SCAN 0

The SCAN command will return two elements: the new cursor position and an array of keys. 

initiating the scan in redis cli
  1. If there are more keys that cannot be scanned in one go then continue issuing the SCAN command with the new cursor until it returns 0, indicating no more keys to scan.
  2. Collect keys from each output array until all keys have been scanned.
continue scanning until it returns 0
  1. Use the MATCH option to filter keys by a specific pattern during scanning, similar to KEYS but more efficiently:
SCAN 0 MATCH user*

Filters the scan results to only include keys that match the specified pattern.

scanning keys with specific pattern

Common Issues When Listing Keys in Redis

Working with Redis, especially when listing keys using the Command Line Interface on Ubuntu, you might run into a few common issues. Whether it’s a technical glitch, slow performance, or access issues, I will help you to fix them quickly and keep your Redis database running smoothly. Here’s how you can identify and resolve these problems:

  • 🔄 High CPU Usage: The KEYS command might cause your CPU to spike if your database is large. This happens because KEYS scans every key in your database. To resolve this replace KEYS with SCAN, which processes keys in batches, reducing the load on your CPU and maintaining server responsiveness.
  • 🚫 Command Blocked: Using KEYS can freeze your Redis because it locks the database while scanning. This blockage stops other commands from executing until it’s done. Opt for the SCAN command that allows the database to handle other operations simultaneously by breaking the task into smaller parts.
  • 📊 Incomplete Key Listings: You might think SCAN is skipping keys if you don’t follow through the entire cursor cycle until it resets to 0. Always continue to run SCAN until the cursor output is 0, ensuring you have covered the entire database.
  • 🔒 Permission Errors: If you can’t access certain keys, it might be due to restricted permissions set in Redis. Review and modify the Redis Access Control Lists (ACLs) to provide the necessary permissions for your user account to access or modify the keys.
  • 🐌 Slow Response Times: When you use SCAN with a low count, especially in large databases, it can slow down responses. Increase the COUNT parameter in the SCAN command to fetch more keys per batch, speeding up the process while ensuring it doesn’t overload your system.
  • 🧩 Pattern Mismatch: If you can’t find keys with the MATCH option, your pattern might not match the actual keys. Double-check your pattern for errors and ensure it accurately reflects the naming convention used in your Redis keys.
  • 🔗 Connection Issues: Problems with connecting to Redis via CLI often arise if Redis isn’t running or if there’s a configuration error. Verify that the Redis server is active (sudo systemctl status redis) and check your connection parameters (host, port, password) to ensure they are correct.
  • 📑 Output Overload: Getting too many keys at once can be overwhelming and hard to handle manually. Use shell scripting to handle large outputs. For example, you can pipe SCAN results into tools like grep for filtering or redirect output to a file for easier processing (SCAN 0 MATCH user:* > redis_keys.txt).

Conclusion

In this guide, I walked you through using the KEYS and SCAN commands to get all keys in Redis keys on Ubuntu. We also looked at some common issues you might face and how to solve them. These tools and tips are crucial for keeping your Redis database running smoothly.

To further enhance your skills with Redis on Ubuntu, consider exploring topics that build on your current knowledge. Learn how to use the grep OR condition to refine command-line searches. Explore listing all services in Ubuntu, which will aid in managing and troubleshooting Redis effectively. Also, mastering the systemctl command can provide deeper control over your system’s services, including Redis.

Frequently Asked Questions

  1. How can I limit the output of keys when using the KEYS command to improve readability?

    To limit the output when using the KEYS command for better readability, you can pipe the results to other command line tools like head or tail. For example, redis-cli KEYS '*' | head -10 will display only the first 10 keys.

  2. How do you restore Redis keys from a backup using the command line?

    To restore Redis keys from a backup using the command line, you can use the redis-cli tool to load a dump file back into your Redis server. Simply use the command cat dump.rdb | redis-cli -x restore. Ensure your Redis server allows this operation by configuring appropriate directives.

  3. How to handle special characters in keys when using the SCAN command?

    When using the SCAN command to handle keys with special characters, ensure to escape these characters in your command line syntax properly. For instance, if your keys contain spaces or special symbols, enclose the pattern in quotes, like SCAN 0 MATCH "user:*name with space*".

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

How to Install and Use Htop in Linux? [3 Best Methods to Install]

Next Post

How to View Linux File Timestamps? [3 Easy Methods]

Leave a Reply

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

Read next