REDIS Scripting – a quick intro

In Caches, Distributed Systems, Performance, Software Development by Prabhu Missier

Lua scripting can be used to increase the speed of REDIS operations as opposed to coding the operations in the language of your application. What follows is a simple example to get the capitals of countries using a couple of Lua scripts.

Let’s assume we have a sorted set of countries

zadd country 1 India 2 USA 3 Japan

Now we also create a hash set which maps countries with their capitals

hmset country_cap India "New Delhi" USA "Washington" Japan Tokyo Russia Moscow France Paris

eval "local clist = redis.call('zrange', KEYS[1], 0, -1); return redis.call('hmget', KEYS[2], unpack(clist));" 2 country country_cap

First we call zrange with the key country passed as KEYS[1].The result is stored in a local variable clist. This local variable is then passed to the next call using unpack where the hash map is searched for the capitals. The arguments passed are the number of keys which is 2 in this case, the country key for the zrange call and the country_cap key for the hmget call. Running the above script gives us the result seen below:

1) "New Delhi"
2) "Washington"
3) "Tokyo"

Scripts can also be saved as shown below.

script load "local clist = redis.call('zrange', KEYS[1], 0, -1); return redis.call('hmget', KEYS[2], unpack(clist));"

On executing the above from the REDIS command line you will obtain a hash like so :

"338e3f034f9a59a6c9fef6919d24d1d98560fdf9"

Now this hash can be used to execute the script instead of typing out the script everytime

evalsha 338e3f034f9a59a6c9fef6919d24d1d98560fdf9 2 country country_cap

Note that the arguments are passed at the very end.

You can check if a script exists using

script exists 338e3f034f9a59a6c9fef6919d24d1d98560fdf9

and flush all scripts using

script flush