【问题标题】:redis - HSCAN MATCH only "first level"redis - HSCAN MATCH 仅“第一级”
【发布时间】:2021-03-09 18:53:55
【问题描述】:

我正在使用带有哈希的 Redis 来索引来自文件系统的真实路径,例如:

HSET example "/dir" "some value"
HSET example "/dir/sub-dir" "some value"
HSET example "/dir/sub-dir-2" "some value"
HSET example "/dir/sub-dir/sub-sub-dir" "some value"
HSET example "/dir/sub-dir/another-sub-sub-dir" "some value"

现在我需要获取“目录的内容”。我试过用HSCAN:

HSCAN example 0 MATCH "/dir/*"

但是有了这个,我得到了这个目录中的每一个路径,但我应该只得到:

/dir/sub-dir
/dir/sub-dir-2

是否有可能通过匹配模式得到这个?

【问题讨论】:

  • 您可以使用 Lua 脚本进行更高级的模式匹配。检查this 以供参考。您应该将模式替换为:/dir/[^\/]*$,并调用HSCAN 而不是SCAN

标签: redis


【解决方案1】:

AFAIK,不,Redis 的模式匹配是类似 glob 的,不允许这样做。

不过,您可以为此目的使用服务器端 Redis Lua script,可能是这样的:

local key = KEYS[1]
local cur = ARGV[1]
local path = ARGV[2]
local pattern = path .. '*'
local plen = string.len(pattern)

local r = redis.call('HSCAN', key, cur, 'MATCH', pattern)
local rlen = #r[2]
while rlen > 0 do
  local f = r[2][rlen-1]
  if string.find(f, '/', plen) then
    -- Remove field and value
    for i = 0,1 do
      table.remove(r[2], rlen)
      rlen = rlen - 1
    end
  else
    rlen = rlen - 2
  end
end

return r
~/work/redis-io master*                                                                                                               15:59:55
❯ redis-cli --eval /tmp/hscanfirstlv.lua example , 0 "/dir/"
1) "0"
2) 1) "/dir/sub-dir"
   2) "some value"
   3) "/dir/sub-dir-2"
   4) "some value"

执行示例:

$ cat myscript.lua | redis-cli SCRIPT LOAD -x
"4a95e1a03bfeeb1cb9e433862dce47b63981fbdc"
$ redis-cli EVALSHA "4a95e1a03bfeeb1cb9e433862dce47b63981fbdc" 1 example 0 "/dir/"
1) "0"
2) 1) "/dir/sub-dir"
   2) "some value"
   3) "/dir/sub-dir-2"
   4) "some value"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-21
    • 2022-01-08
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 2016-03-16
    相关资源
    最近更新 更多