本文介绍了根据哈希键名称批量删除redis哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与此类似,但是需要一种解决方案来解决哈希而不是普通密钥:

Similar to this, but needing a solution for hashes instead of plain keys: How to atomically delete keys matching a pattern using Redis

我有一堆带有前缀的哈希,例如:前缀:"

I have a bunch of hashes with prefix like: "prefix:"

在每个哈希下都有一堆键,例如:"cc_XX",其中"XX"是2个字母的代码.

Under each hash are a bunch of keys like: "cc_XX", where "XX" is a 2 letter code.

我需要一些方法来遍历我的所有redis散列,并删除每个cc_XX子键的某些方法,并且正在寻找一种cli/lua方式来做到这一点(两者都不适合).

I need to some how loop through all my redis hashes, and delete each of the cc_XX sub keys some how, and am looking for a cli/lua way to do this (not great with either).

任何建议将不胜感激.

推荐答案

以下 EVAL脚本应该可以你想要什么:

The following EVAL script should do what you want:

local keys = redis.call('KEYS',KEYS[1])
for i,k in ipairs(keys) do
    local res = redis.call('HKEYS',k)
    for j,v in ipairs(res) do
        if string.find(v,ARGV[1]) then
            redis.call('HDEL',k,v)
        end
    end
end

您需要通过提供以下参数来调用它:

You need to call it by providing the following parameters:

EVAL <script> 1 prefix:* cc_..

请注意,它会阻塞Redis事件循环,直到脚本完成为止,因此,如果您有大量键,它可以冻结Redis一段时间.原子性是有代价的.

Please note it blocks the Redis event loop until the script is complete, so it can freeze Redis for a while if you have a large number of keys. Atomicity has a price.

更新:

如果您不需要原子性,那么以下脚本将避免阻塞Redis太长时间(但请注意,如果您拥有大量全局键,或者如果您的哈希对象之一很大,它将仍会阻塞:无法避免这种情况.)

If you don't need the atomicity, then the following script will avoid blocking Redis for too long (but please note, it will still block if you have a huge global number of keys or if one of your hash object is huge: there is no way to avoid this).

./redis-cli keys 'prefix:*' | awk '
BEGIN {
    script = "local res = redis.call('\''HKEYS'\'',KEYS[1]); \
          for j,v in ipairs(res) do                          \
            if string.find(v,ARGV[1]) then                   \
              redis.call('\''HDEL'\'',KEYS[1],v);            \
            end                                              \
          end"
}
{
    printf "EVAL \"%s\" 1 %s cc_..\n", script, $1
}' | ./redis-cli

(已通过bash测试)

(tested with bash)

这篇关于根据哈希键名称批量删除redis哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:13