两个列表之间的Redis差异? [英] Redis diff between two lists?

查看:69
本文介绍了两个列表之间的Redis差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,sDiff 仅适用于集合.但是我怎样才能得到索引列表之间的差异?

As I know sDiff works only with sets. But how can i get diff between indexed lists?

....
$Redis->lPush("KEY1", "Value1");
$Redis->lPush("KEY1", "Value2");
$Redis->lPush("KEY1", "Value3");

$Redis->lPush("KEY2", "Value1");
$Redis->lPush("KEY2", "Value3");
$Redis->lPush("KEY2", "Value4");

$Redis->sDiff("KEY1", "KEY2");
....

推荐答案

没有内置命令 - 您的选择是拉两个列表并在客户端执行比较(用于差异),或者编写一个使用 EVAL 命令运行的 Lua 脚本在服务器端执行.以下是此类脚本的示例:

There is no built-in command for that - your options are either pull the two lists and perform the comparison (for diff) in the client, or write a Lua script that is run with the EVAL command to perform it server-side. Here's an example for such a script:

--[[ 
LDIFF key [key ...]
Returns the elements in the first list key that are also present in all other
keys.
]]--

-- A utility function that converts an array to a table
local function a2t(a)
  local t = {}
  for i, v in ipairs(a) do
    t[v] = true
  end
  return t
end

-- A utility function that converts a table to an array
local function t2a(t)
  local a = {}
  for k, _ in pairs(t) do
    a[#a+1] = k
  end
  return a
end

-- main
local key = table.remove(KEYS,1)
local elems = a2t(redis.call('LRANGE', key, 0, -1))

-- iterate remaining keys
while #KEYS > 0 do
  key = table.remove(KEYS,1)
  local check = a2t(redis.call('LRANGE', key, 0, -1))
  -- check each element in the current key for existence in the first key
  for k, _ in pairs(elems) do
    if check[k] then
      elems[k] = nil
    end
  end
end

-- convert the table to an array and reply
return t2a(elems)

使用 redis-cli 运行它看起来像这样:

Running this with redis-cli looks like this:

$ redis-cli LPUSH key1 value1 value2 value3
(integer) 3
$ redis-cli LPUSH key2 value1 value3 value4
(integer) 3
$ redis-cli --eval ldiff.lua key1 key2
1) "value2"

这篇关于两个列表之间的Redis差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆