How to count number of elements in Redis using Lua script

If you want to count the number of keys present in your redis server matching to certain pattern, you might get all the keys using KEYS command and then count the occurrences. This is very inefficient way as you will end up getting all the keys on your server when you are only interested in their count. So instead we can run a Lua Script which will get executed at redis server and return number of items rather then all the items.

 String key = getRedisCacheKey(xObj,false);
            String script = "local count=0 local matches =redis.call('keys','" + key
                    + ":*') for _,key in ipairs(matches) do    count = count + 1  end return count ";
            Object count = cMgr.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 *