Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple-get in one go - Redis

Tags:

redis

lua

jedis

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.

like image 747
user_ab Avatar asked Feb 26 '15 04:02

user_ab


2 Answers

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
like image 137
Uyghur Lives Matter Avatar answered Nov 12 '22 02:11

Uyghur Lives Matter


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

like image 35
Itamar Haber Avatar answered Nov 12 '22 01:11

Itamar Haber