user_ab
user_ab

Reputation: 225

Multiple-get in one go - Redis

How can we use lua scripting to implement multi-get.

Let's say if I've set name_last to Beckham and name_first to David. What should the lua script be in order to get both name_last and name_first in one go?

I can implement something like:

eval "return redis.call('get',KEYS[1])" 1 foo

to get the value of single key. Just wondering on how to enhance that scripting part to get values related to all keys (or multiple keys) by just making one call to redis server.

Upvotes: 8

Views: 9752

Answers (2)

Itamar Haber
Itamar Haber

Reputation: 49942

Do a loop over the KEYS table and for each store its GET response in a take that you return. Untested code:

local t = {}
for _, k in pairs(KEYS) do
  t[#t+1] = redis.call('GET', k)
end
return t

P.S. You can also use MGET instead btw :)

Upvotes: 4

ohmu
ohmu

Reputation: 19752

First, you want to send the fields you want to return to EVAL (the 0 indicates that there are no KEYS so these arguments will be accessible from ARGV):

eval "..." 0 name_last name_first

Second, you can query the values for the individual fields using MGET:

local values = redis.call('MGET', unpack(ARGV))

Third, you can maps the values back to the field names (the index of each value corresponds to the same field):

local results = {}
for i, key in ipairs(ARGV) do
  results[key] = values[i]
end
return results

The command you'll end up executing would be:

eval "local values = redis.call('MGET', unpack(ARGV)); local results = {}; for i, key in ipairs(ARGV) do results[key] = values[i] end; return results" 0 name_last name_first

Upvotes: 6

Related Questions