Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis delete all keys except keys that start with

Tags:

redis

My redis collection contains many keys

I want to be able to flush them all except all the keys that start with:

"configurations::"

is this possible?

like image 500
amitben Avatar asked Nov 06 '15 07:11

amitben


2 Answers

You can do this

redis-cli KEYS "*" | grep -v "configurations::" | xargs redis-cli DEL

List all keys into the redis, remove from the list keys that contains "configurations::" and delete them from the redis

Edit As @Sergio Tulentsev notice it keys is not for use in production. I used this python script to remove keys on prodution redis. I stoped replication from master to slave before call the script.

#!/usr/bin/env python
import redis
import time

pattern = "yourpattern*"

poolSlave = redis.ConnectionPool(host='yourslavehost', port=6379, db=0)
redisSlave = redis.Redis(connection_pool=poolSlave)

poolMaster = redis.ConnectionPool(host='yourmasterhost', port=6379, db=0)
redisMaster = redis.Redis(connection_pool=poolMaster)


cursor = '0'
while cursor != 0:
        cursor, data = redisSlave.scan(cursor, pattern, 1000)
        print "cursor: "+str(cursor)
        for key in data:
                redisMaster.delete(key)
                print "delete key: "+key
        # reduce call per second on production server
        time.sleep(1) 
like image 79
khanou Avatar answered Nov 18 '22 11:11

khanou


The SCAN & DEL approach (as proposed by @khanou) is the best ad-hoc solution. Alternatively, you could keep an index of all your configurations:: key names with a Redis Set (simply SADD the key's name to it whenever you create a new configurations:: key). Once you have this set you can SSCAN it to get all the relevant key names more efficiently (don't forget to SREM from it whenever you DEL though).

like image 42
Itamar Haber Avatar answered Nov 18 '22 11:11

Itamar Haber