2016-09-21 77 views
1

我試圖用Lua中搜索字段值在哈希,我做錯了什麼:) 我有鑰匙「文章」,這是zset控股文章ID和鍵文章:N其中「n」是商品編號。 下面的腳本:搜索在Redis的評估Lua中

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 

請你能幫助我嗎?

+0

不管該情況的問題,你應該注意到的是在腳本中使用的所有鍵名應通過使用'KEYS'參數表 - 動態訪問密鑰(例如基於Sorted Set範圍的內容)不能保證在羣集環境中工作。 –

回答

2

你從Lua返回的表,必須是一個數組,其指數從1盯着。

但是,在您的示例中,只有第二篇文章符合條件,其索引是2。實際上,您將表格設置爲:​​。由於返回的表不是一個索引從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 
+0

謝謝您的回覆@for_stack,終於我有在服務器端,這是我想簡單的搜索了一些解決會比在客戶端的匹配,因爲只有相關的數據將被轉移:) – ivan73

+1

@ ivan73只是爲了提醒好得多:你應該對太複雜的lua腳本非常小心。由於它以原子方式運行,並且Redis是單線程的,因此會阻止Redis進程。尤其是,如果腳本太複雜(做太多工作),它會阻塞Redis很長一段時間。 –

0

試試這個條件

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

+0

感謝您的評論Nikita,我試過了,但它不起作用。 – ivan73