一种方法是将数据存储在列表中并使用 Lua 脚本进行检索。首先,对于 (Sn,Tn) 形式的元组,像这样插入它:
LPUSH myKey S1:T1
LPUSH myKey S2:T2
... and so on
然后,使用下面的 Lua 脚本:
local function split(div,str)
if (div=='') then return false end
local pos,arr = 0,{}
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1))
pos = sp + 1
end
table.insert(arr,string.sub(str,pos))
return arr
end
local key = KEYS[1]
local sVal = ARGV[1]
local tVal = tonumber(ARGV[2])
local cVal = tonumber(ARGV[3])
local length = redis.call("LLEN", key)
if (tonumber(length) == 0) then
return nil
end
local data = redis.call("LRANGE", key, 0, tonumber(length))
local retval = {}
for index,val in pairs(data) do
local parts = split(":", val)
if (parts[1] == sVal and math.abs(tonumber(parts[2]) - tVal) <= cVal) then
table.insert(retval, val)
end
end
return retval
将其保存为script.lua 并执行:
$ redis-cli "$(cat script.lua)" 1 myKey sValue tValue cValue
这将返回与S1 == S2 and |T1 - T2| <= C 匹配的所有元组(Sn:Tn 形式)。