使用通配符删除redis中的散列属性



在redis中,我们可以使用通配符,如

KEYS foo* ->查找键

现在我想使用通配符删除hashmap的特定字段。考虑如下:创建hashmap

 HMSET myhash f "g" field1 "Hello" field2 "World" 

现在我想删除键使用通配符,如

 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;

该脚本复杂度 0 (n)。脚本返回与给定模式匹配的已删除字段。看看绳子。匹配教程: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.+']));

最新更新