amitben
amitben

Reputation: 700

Redis delete all keys except keys that start with

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?

Upvotes: 6

Views: 8353

Answers (3)

Itamar Haber
Itamar Haber

Reputation: 49942

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).

Upvotes: 2

khanou
khanou

Reputation: 1454

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) 

Upvotes: 14

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

Yes, it's possible. Enumerate all the keys, evaluate each one and delete if it fits the criteria for deletion.

There is no built-in redis command for this, if this is what you were asking.

It might be possible to cook up a Lua script that will do this (and it'll look to your app that it's a single command), but still it's the same approach under the hood.

Upvotes: 0

Related Questions