在 Redis 中搜索并评估 Lua 脚本

我正在尝试使用 Lua 脚本搜索哈希中的字段值,但是我的操作有误 :) 我有一个键"articles",它是一个保存文章 ID 的 zset,还有 article:n 键,其中 "n" 就是文章编号。 接下来的脚本:

local ids = redis.call("zrange", 'articles', '0', '-1')
local ret = {}
for k, id in pairs(ids) do
    local row = redis.call("hgetall", "article:"..id)
    ret[k] = row
end
return ret

它会返回以下结果:

1)  1) "slug"
    2) "first-title"
    3) "title"
    4) "first title"
2)  1) "slug"
    2) "second-title"
    3) "title"
    4) "second title"

然后,我正在尝试在 title 中仅返回包含字符串 "second" 的键,但是它什么都没有返回。

local ids = redis.call("zrange", 'articles', '0', '-1')
local ret = {}
for k, id in pairs(ids) do
    local row = redis.call("hgetall", "article:"..id)
    if (string.find(row[4], "second")) then
        ret[k] = row
    end
end
return ret

请你能帮我吗?

点赞
用户764206
用户764206

尝试以下条件

如果 (string.find(row [4],"second") ~= nil) then
2016-09-21 18:38:50
用户5384363
用户5384363

表格从 lua 返回,必须是一个索引从 1 开始的数组。

然而,在你的例子中,只有第二篇文章符合条件,它的索引是 2。因此实际上你设置的表格是:ret[2] = row。由于返回的表格不是一个索引从 1 开始的数组,Redis 会将其视为一个空数组,因此你什么也得不到。

解决方案:

local ids = redis.call("zrange", 'articles', '0', '-1')
local ret = {}
local idx = 1;  -- 从1开始索引
for k, id in pairs(ids) do
    local row = redis.call("hgetall", "article:"..id)
    if (string.find(row[4], "second")) then
        ret[idx] = row   -- 设置表格
        idx = idx + 1    -- 将索引增加1
    end
end
return ret
2016-09-22 06:28:28