Instead, it provides us with a CLI utility with built-in commands which we can use to manage the databases.
This tutorial will tour how to delete keys in a Redis database.
Requirements
This article assumes you have the following requirements met:
- The latest version of the Redis server is installed on your system.
- Permissions to run commands on the Redis server.
If you have the above requirements, we can proceed.
Redis Insert Keys
Before getting how to delete keys on a Redis database, let us insert some sample data. First, open the terminal and connect to your Redis server.
$ redis-cli
127.0.0.1:6379>
Once connected, you can insert key-value pairs to the database using the SET command.
NOTE: Redis has databases ranging from index 0 to index 15. By default, Redis will use database 0.
Run the command below:
The command above will insert a key called email and the value “[email protected]”
For the sake of this tutorial, we have provided sample data containing a list of IP addresses.
Download the file in the link provided below:
https://www.dropbox.com/s/bqjzswagr673w0v/redis_mock_data.txt.csv?dl=0
Once downloaded, run the command below to insert the data into your Redis database
The command above should insert all the data into your Redis database.
If your server is password secured, use the command as shown:
Replace the password with the password for your server.
Redis Get Values
To retrieve values stored in a Redis database, use the GET command followed by the key you wish to access.
An example from the sample data is as shown:
"3db5:1312:f51c:599c:a9cf:21ce:c135:def4"
The command above should return the IP address stored at the key 1000.
Redis Delete Key
To delete a key in Redis, use the DEL command followed by the key to remove. An example is as shown:
(integer) 1
The command will return the number of keys removed. To learn more about how to delete keys, check this article:
Redis Removes Matching Pattern
By default, Redis does not provide a way to bulk remove keys that match a specific pattern. However, we can leverage the power of the command line to perform this action.
We will use the xargs to build and run commands back to Redis for this one. An example is as shown below:
In this case, we are using the sample datasets provided in the previous sections.
We first scan for all the keys matching the 10*. This should return output as:
100
---
1000
107
Next, we construct a single-line command using xargs and pass all the keys to the Redis DEL command.
This should return:
(integer) 12
Here, Redis matches 12 keys and removes them.
HINT: If you use Redis server version 4.0 and above, you can replace the del command with UNLINK.
Closing
In this article, we explored how to work with Redis keys. We discussed how to insert keys into Redis, how to perform mass insertion, retrieve keys, delete single or multiple keys, and finally, how to remove keys matching a specific pattern.
Thanks for reading & Stay Nerdy!!