Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis Python - how to delete all keys according to a specific pattern In python, without python iterating

I'm writing a django management command to handle some of our redis caching. Basically, I need to choose all keys, that confirm to a certain pattern (for example: "prefix:*") and delete them.

I know I can use the cli to do that:

redis-cli KEYS "prefix:*" | xargs redis-cli DEL 

But I need to do this from within the app. So I need to use the python binding (I'm using py-redis). I have tried feeding a list into delete, but it fails:

from common.redis_client import get_redis_client cache = get_redis_client() x = cache.keys('prefix:*')   x == ['prefix:key1','prefix:key2'] # True 

# And now

cache.delete(x)  

# returns 0 . nothing is deleted

I know I can iterate over x:

for key in x:    cache.delete(key) 

But that would be losing redis awesome speed and misusing its capabilities. Is there a pythonic solution with py-redis, without iteration and/or the cli?

Thanks!

like image 477
alonisser Avatar asked Feb 23 '14 22:02

alonisser


People also ask

How do I delete all keys matching a pattern in Redis?

Redis does not offer a way to bulk delete keys. You can however use redis-cli and a little bit of command line magic to bulk delete keys without blocking redis. This command will delete all keys matching users:* If you are in redis 4.0 or above, you can use the unlink command instead to delete keys in the background.

How do I clear a key in Redis?

Redis Commands There are two major commands to delete the keys present in Redis: FLUSHDB and FLUSHALL. We can use the Redis CLI to execute these commands. The FLUSHDB command deletes the keys in a database. And the FLUSHALL command deletes all keys in all databases.

How do I get all Redis keys?

To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.

What is StrictRedis?

redis-py 3.0 drops support for the legacy "Redis" client class. "StrictRedis" has been renamed to "Redis" and an alias named "StrictRedis" is provided so that users previously using "StrictRedis" can continue to run unchanged. Here is the line from redis-py code which defines StrictRedis (link): StrictRedis = Redis.


1 Answers

Use SCAN iterators: https://pypi.python.org/pypi/redis

for key in r.scan_iter("prefix:*"):     r.delete(key) 
like image 148
Alex Toderita Avatar answered Sep 19 '22 02:09

Alex Toderita