问题描述
在 Redis 中,keys user*
将打印所有以 user
开头的键.例如:
In Redis, keys user*
will print all keys starting with user
.For example:
keys user*
1) "user2"
2) "user1"
现在,我希望打印所有不以 user
开头的键.我怎么能这样做?
Now, I want all keys that don't start with user
to be printed.How could I do that?
推荐答案
重要提示: 始终使用 SCAN
而不是(邪恶)
IMPORTANT: always use SCAN
instead of (the evil) KEYS
Redis 的模式匹配在功能上有些限制(请参阅 ) 并且不提供您寻求 ATM 的内容.也就是说,请考虑以下可能的路线:
Redis' pattern matching is somewhat functionally limited (see the implementation of stringmatchlen
in util.c) and does not provide that which you seek ATM. That said, consider the following possible routes:
- 扩展
stringmatchlen
以符合您的要求,可能将其作为 PR 提交. - 考虑您要尝试做什么 - 除非您对它们进行索引,否则获取键的子集总是效率低下的,请考虑跟踪所有非用户键的名称(例如在 Redis 集中).
- 如果您真的坚持扫描整个键空间并匹配否定模式,那么实现这一点的一种方法是使用一点 Lua 魔法.
- Extend
stringmatchlen
to match your requirements, possibly submitting it as a PR. - Consider what you're trying to do - fetching a subset of keys is always going to be inefficient unless you index them, consider tracking the names of all non-user keys (i.e.g. in a Redis Set) instead.
- If you are really insistent on scanning the entire keyspace and match against negative patterns, one way to accomplish that is with a little bit of Lua magic.
考虑以下数据集和脚本:
Consider the following dataset and script:
127.0.0.1:6379> dbsize
(integer) 0
127.0.0.1:6379> set user:1 1
OK
127.0.0.1:6379> set use:the:force luke
OK
127.0.0.1:6379> set non:user a
OK
Lua(另存为 scanregex.lua
):
local re = ARGV[1]
local nt = ARGV[2]
local cur = 0
local rep = {}
local tmp
if not re then
re = ".*"
end
repeat
tmp = redis.call("SCAN", cur, "MATCH", "*")
cur = tonumber(tmp[1])
if tmp[2] then
for k, v in pairs(tmp[2]) do
local fi = v:find(re)
if (fi and not nt) or (not fi and nt) then
rep[#rep+1] = v
end
end
end
until cur == 0
return rep
输出 - 第一次正则匹配,第二次补码:
Output - first time regular matching, 2nd time the complement:
foo@bar:~$ redis-cli --eval scanregex.lua , "^user"
1) "user:1"
foo@bar:~$ redis-cli --eval scanregex.lua , "^user" 1
1) "use:the:force"
2) "non:user"
这篇关于如何获取与redis中的特定模式不匹配的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!