我正在尝试使用 Lua 脚本在哈希中搜索字段值,但我做错了:) 我有关键的“文章”,它是 zset 持有文章 ID 和关键文章: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"
我试图包含条件以仅返回标题中包含字符串“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
你能帮帮我吗?
最佳答案
你从lua返回的表,必须是一个索引从1
开始的数组。
但是,在您的示例中,只有第二篇文章符合条件,其索引为2
。因此,您实际上是将表设置为:ret[2] = row
。由于返回的表不是索引从 1
开始的数组,因此 Redis 将其视为空数组,您什么也得不到。
解决方案:
local ids = redis.call("zrange", 'articles', '0', '-1')
local ret = {}
local idx = 1; -- index starting from 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 -- set table
idx = idx + 1 -- incr index by 1
end
end
return ret
关于lua - 在 Redis 中搜索评估 Lua 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39623431/