Redis Python - 如何根据特定模式删除所有键在python中,无需python迭代 [英] Redis Python - how to delete all keys according to a specific pattern In python, without python iterating
问题描述
我正在编写一个 django 管理命令来处理我们的一些 redis 缓存.基本上,我需要选择所有键,确认某个模式(例如:前缀:*")并删除它们.
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.
我知道我可以使用 cli 来做到这一点:
I know I can use the cli to do that:
redis-cli KEYS "prefix:*" | xargs redis-cli DEL
但我需要在应用程序中执行此操作.所以我需要使用 python 绑定(我使用的是 py-redis).我曾尝试将列表输入到删除中,但失败了:
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
# 现在
cache.delete(x)
# 返回 0 .什么都没有删除
# returns 0 . nothing is deleted
我知道我可以遍历 x:
I know I can iterate over x:
for key in x:
cache.delete(key)
但这将失去 redis 惊人的速度并滥用其功能.py-redis 是否有 pythonic 解决方案,无需迭代和/或 cli?
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?
谢谢!
推荐答案
我认为
for key in x: cache.delete(key)
非常好且简洁.delete
真的要一次一个键,所以你必须循环.
is pretty good and concise. delete
really wants one key at a time, so you have to loop.
否则,这个之前的问答 为您指明了一个基于 lua 的解决方案.
Otherwise, this previous question and answer points you to a lua-based solution.
这篇关于Redis Python - 如何根据特定模式删除所有键在python中,无需python迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!