redis delete all keys with prefix

redis delete all keys with prefix
Reading Time: < 1 minute

Redis, one of the most popular open-source in-memory databases, provides a simple and straightforward way to delete all keys with a given prefix. This can be done with the help of the **KEYS** and **DEL** commands. First, use **KEYS** to find all keys with a given prefix. This command will search all keys within the given database and return all matching keys in an array. Next, use **DEL** to delete all these keys. For example, if you wanted to delete all

Delete all the keys by a given prefix in a Redis cluster.

Let’s ping our Redis instance

   
redis-cli -h myhost.com -p 6379 ping
   

Set some keys

   
redis-cli -h myhost.com -p 6379 SET dev1 "val1"
redis-cli -h myhost.com -p 6379 SET dev2 "val2"
redis-cli -h myhost.com -p 6379 SET dev3 "val3"
   

Get one key

   
redis-cli -h myhost.com -p 6379 KEYS dev1 
   

Delete one key

   
redis-cli -h myhost.com -p 6379 DEL dev1 
   

Now let’s go with our massive deletion algorithm but before making any deletion let’s test the algorithm without making changes.

   
for key in `echo 'KEYS dev*' | redis-cli -c -h myhost.com -p 6379 | awk '{print $1}'`
  do echo KEYS $key
done | redis-cli -c -h myhost.com -p 6379
   

And then when you are sure, go ahead with the deletion

   
for key in `echo 'KEYS dev*' | redis-cli -c -h myhost.com -p 6379 | awk '{print $1}'`
  do echo DEL $key
done | redis-cli -c -h myhost.com -p 6379
   

In case you are not using a cluster just remove the -c options from redis-cli

Photo by Sam Pak on Unsplash


About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Join 22 other subscribers

Leave a Reply

Discover more from javaniceday.com

Subscribe now to keep reading and get access to the full archive.

Continue reading