How to delete Redis keys using pattern
So Googling this question show a common approach using
KEYS command and then pipe them to
DEL command, which looks something like this in Lua script
local keys = redis.call('keys', ARGV) for i=1,#keys,5000 do redis.call('del', unpack(keys, i, math.min(i+4999, #keys))) end return keys
Doing things like this would be fine for development where the keyspace is small and frequent of use is low.
However, if you were to do this at a larger keyspace and a lot more frequent, the
KEYS command will block Redis instance and making other commands to fail.
The alternative is to use
SCAN and loop until the cursor is 0. A naive implementation is like below.
redis.replicate_commands() local matches = redis.call('scan', '0', 'match', ARGV, 'count', '10000') while matches ~= "0" do for i=1,#matches,5000 do redis.call('del', unpack(matches, i, math.min(i+4999, #matches))) end matches = redis.call('scan', matches) end return matches