How to efficiently delete multiple keys in redis using Lua script

Suppose you want to delete thousands of keys from your redis server based on certain pattern. You might end up making multiple DEL command calls to your redis server which obviously would be very inefficient. So instead of that we can execute a LUA script which will get executed at the redis server and delete all the matching keys.

This way you will make only one call to redis instead of multiple. This can save you many seconds if not minutes

 String script = "local count=0 local exists = 0 "
                               + "local matches =redis.call('keys','" + cacheKey+ ":*') "
                               + "count = #matches "
                               + " for i,name in ipairs(matches) do   "
                                   + " if(i <= "  +  delCount  +  ") then "
                                      + "redis.call('del',name) "
                                       + "count = count - 1 "
                                   + "end "
                               + "end "
                               + "redis.call('hset','" + cacheKey + "','" + REDISSTATS_CACHE_CURRENTCOUNT + "',count) "
 
                               + "return count ";
                      cacheMgr.eval(script);

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *