【问题标题】:Searching in Redis evaluating Lua script在 Redis 中搜索评估 Lua 脚本
【发布时间】:2016-09-22 14:28:28
【问题描述】:

我正在尝试使用 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"

我试图包含条件以仅返回标题中包含字符串“秒”的键,但它什么也不返回。

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

你能帮帮我吗?

【问题讨论】:

  • 不管条件有什么问题,您应该注意脚本中使用的所有键名都应该使用KEYS 参数表传递 - 动态访问键(例如,基于Sorted Set range) 不能保证在集群环境中工作。

标签: lua redis


【解决方案1】:

你从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

【讨论】:

  • 感谢您的回复@for_stack,最后我有了一些在服务器端进行简单搜索的解决方案,我认为这比在客户端匹配要好得多,因为只会传输相关数据:)
  • @ivan73 只是为了提醒:你应该非常小心过于复杂的 lua 脚本。由于它以原子方式运行,并且 Redis 是单线程的,因此它会阻塞 Redis 进程。特别是如果脚本太复杂(做太多工作),它会阻塞 Redis 很长时间。
【解决方案2】:

试试这个条件

if (string.find(row[4], "second") ~= nil) then

【讨论】:

  • 感谢 Nikita 的评论,我试过了,但还是不行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-28
  • 1970-01-01
  • 2015-10-27
  • 2020-11-08
  • 2017-05-05
  • 2014-07-31
  • 2016-08-10
相关资源
最近更新 更多