如何在 Redis 中获取所有带前缀的 hashmap 匹配?

How to get all hashmap match with prefix in Redis?

我有以下格式的 redis 数据:

HMSET name:1 key "value"
HMSET name:2 key "value2"
HMSET name:3 key "value3"
HMSET name:a key "valuea"

如何获取前缀为“name:”的所有hashmap,结果相同:

name:1 key "value"
name:2 key "value2"
name:3 key "value3"

您想使用 SCAN 而不是 KEYS,因为 KEYS 可能会阻塞您的服务器太久。

您想按哈希映射类型进行过滤。在 How can I get all of the sets in redis?

中查看更多信息

然后,您想将 field-values 附加到响应中。为此你需要 Lua Scripting.

这个脚本应该让你开始:

local result = redis.call('SCAN', ARGV[1], 'MATCH', ARGV[2])
local filtered = {}
for _,key in ipairs(result[2]) do
    if redis.call('TYPE', key).ok == ARGV[3] then
        local keyWithHash = {}
        keyWithHash[1] = key
        keyWithHash[2] = redis.call('HGETALL', key)
        table.insert(filtered, keyWithHash)
    end
end
result[2] = filtered
return result

如果您使用的是 Redis 6,您可以通过使 SCAN 使用 TYPE 选项而不是通过调用 TYPE command.

一个一个地过滤来优化它

用作:

EVAL "local result = redis.call('SCAN', ARGV[1], 'MATCH', ARGV[2]) local filtered = {} for _,key in ipairs(result[2]) do     if redis.call('TYPE', key).ok == ARGV[3] then      local keyWithHash = {}      keyWithHash[1] = key        keyWithHash[2] = redis.call('HGETALL', key)         table.insert(filtered, keyWithHash)     end end result[2] = filtered return result" 0 0 "name:*" hash

Pre-test:

HMSET name:1 key "value"
HMSET name:2 key "value2"
HMSET name:3 key "value3"
HMSET name:a key "valuea"
SET name:notAhash "asdasd"

测试:

> EVAL "local result ... return result" 0 0 "name:*" hash
1) "0"
2) 1) 1) "name:a"
      2) 1) "key"
         2) "valuea"
   2) 1) "name:3"
      2) 1) "key"
         2) "value3"
   3) 1) "name:2"
      2) 1) "key"
         2) "value2"
   4) 1) "name:1"
      2) 1) "key"
         2) "value"