muffel
muffel

Reputation: 7390

redis: pop from list of not empty, return random element of other list otherwise

There are two lists in redis, having keys l1 and l2. l2 is guaranteed to not be empty. I want to pop (read and remove) the first element of l1, if it is not empty, and otherwise return a random element from l2 without removing it.

Is there any way to achieve this behavior without requiring any client-side technology, framework, logic or an additional roundtrip?

Upvotes: 1

Views: 1035

Answers (2)

Itamar Haber
Itamar Haber

Reputation: 50082

Great answer by Liviu, so this is basically the same script but for any number of lists provided as input via the KEYS table:

for _, k in pairs(KEYS) do
  local m = redis.call('LPOP', k)
  if m then
    return m
  end
end

Upvotes: 2

Liviu Costea
Liviu Costea

Reputation: 3794

lpop on l1 and if no element is returned then lpop on l2 - and you put these in a lua script, so you don't have any additional roundtrip:

local redis_list_member = redis.call('lpop', KEYS[1])
if not redis_list_member then 
    redis_list_member = redis.call('lpop', KEYS[2])
end
return redis_list_member 

And with eval you can pass the script to redis with the 2 lists as parameters

Upvotes: 3

Related Questions