sql >> Base de Datos >  >> NoSQL >> Redis

Redis diff entre dos listas?

No hay un comando incorporado para eso:sus opciones son extraer las dos listas y realizar la comparación (para diff) en el cliente, o escribir un script Lua que se ejecuta con EVAL comando para realizarlo en el lado del servidor. He aquí un ejemplo de un script de este tipo:

--[[ 
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)

Ejecutando esto con redis-cli se parece a esto:

$ 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"