luaredisredisclient

Multiple HMSET to Redis with Lua script


Due to performance, I need to minimize the number of hops to Redis. I am calling HMSET multiple times from C++ code and I am investigating if it is possible to change this by using Lua script and set multiple Redis hash keys with one call to Redis:

HMSET myhash1 field1 "Hello" field2 "World"
HMSET myhash2 field1 "Hello" field2 "World"
HMSET myhash3 field1 "Hello" field2 "World"
...
HMSET myhashN field1 "Hello" field2 "World"

How can I pass to the script multiple hash keys and multiple fields/values?


UPDATE Based on Itamar Haber comment, I figured out that my problem was the comma with a space missing between the KEYS and ARGV values -

I ended up to the following script:

local k = 1 
for i=1,  #KEYS do
    if redis.call('hmset', KEYS[i], ARGV[k], ARGV[k+1], ARGV[k+2], ARGV[k+3]) == 1 then
        return 1
    end 
    k = k + 4 
end                                                                                                                                                                                             
return 0

redis-cli --eval /var/tmp/script.lua myhash1 myhash2 , field1 "Hello" field2 "World" field1 "Hello" field2 "World"

I am not sure if it can be optimized further to avoid repeating the field names or passing arbitrary number of fields/values for each key.


Solution

  • To minimize the hops you can use pipelining instead - simpler and has the desired effect.

    A script can also minimize the hops. Use the KEYS array to pass you Hash key names to the script and the ARGV array to provide the fields and values.