data-structures - Redis区间查询

标签 data-structures redis processing-efficiency database nosql

我有元组 (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

这将返回匹配 Sn:Tn 的所有元组(以 S1 == S2 and |T1 - T2| <= C 形式) .

关于data-structures - Redis区间查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37012512/

相关文章:

c - 如何处理索引大于 32 位的数据结构?

java - 检查字符串的所有字符是否包含相同的次数

google-app-engine - 删除祖先后,子数据存储对象会怎样?

docker: MISCONF Redis配置保存RDB快照

push vs. mov(stack vs. near memory)的成本,以及函数调用的开销

java - 具有多个可变查找属性的集合的正确数据结构

node.js - 如何从在 docker 容器中运行的应用程序连接在我的机器上运行的 redis

javascript - 从 redis 命令返回的数组中获取数据

python - 在 python 中重复 y/n 问题的有效方法

arrays - 数组和二叉搜索树在效率上有什么区别?