Redis区间查询
Redis interval query
我有元组形式的数据 (S, T),其中 S 是字符串,T 是整数。 S 和 T 都不是唯一的,而它们的组合是唯一的。我需要获取 S1 == S2
和 |T1 - T2| <= C
的所有元组。有可能用 Redis 高效地做事吗?
一种方法是将数据存储在列表中并使用 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
这将 return 所有匹配 S1 == S2 and |T1 - T2| <= C
.
的元组(以 Sn:Tn
形式)
我有元组形式的数据 (S, T),其中 S 是字符串,T 是整数。 S 和 T 都不是唯一的,而它们的组合是唯一的。我需要获取 S1 == S2
和 |T1 - T2| <= C
的所有元组。有可能用 Redis 高效地做事吗?
一种方法是将数据存储在列表中并使用 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
这将 return 所有匹配 S1 == S2 and |T1 - T2| <= C
.
Sn:Tn
形式)