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!
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.
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.
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.
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.
Use SCAN iterators: https://pypi.python.org/pypi/redis
for key in r.scan_iter("prefix:*"): r.delete(key)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With