在redis中,我们可以像这样使用通配符,
KEYS foo*
-> 查找 key 。
现在我想使用通配符删除 hashmap 的特定字段。考虑以下例如。 创建 HashMap
HMSET myhash f "g" field1 "Hello" field2 "World"
现在我想使用通配符删除 key
DEL myha*
这可能吗?
我还想使用像
这样的通配符从 SET 中删除特定字段DEL myhash field*
这也可以吗?
提前致谢。
最佳答案
要使用通配符从 SET 中删除特定字段,您可以使用此 LUA 脚本:
-- ARGV[1] - hash key
-- ARGV[1] - lua pattern
local fields = redis.call("HKEYS", ARGV[1]);
local retVal = {};
for key, value in pairs(fields) do
if (string.match(value, ARGV[2])) then
table.insert(retVal, value);
redis.call("HDEL", ARGV[1], value);
end
end
return retVal;
此脚本的复杂度为 O(n)。脚本返回与给定模式匹配的已删除字段。看string.match tutorial到 lua 模式匹配功能。
在 PHP
中使用 phpredis
的示例用法:
$r = new Redis();
$r->connect('127.0.0.1');
for ($i = 1; $i < 1000; $i++) {
$r->hSet('myhash', 'aaa' . mt_rand(0, PHP_INT_MAX), 1);
}
$r->hSet('myhash', 'bad', 1);
$script = <<< SCR
local fields = redis.call("HKEYS", ARGV[1]);
local retVal = {};
for key, value in pairs(fields) do
if (string.match(value, ARGV[2])) then
table.insert(retVal, value);
redis.call("HDEL", ARGV[1], value);
end
end
return retVal;
SCR;
var_dump($r->eval($script, ['myhash', '^b.+']));
关于python - 使用通配符删除redis中的哈希属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23544893/