Redis wildcard DEL as Lua script in Ruby


2014-09-04 · 1 min read

In Redis, KEYS returns keys matching a pattern while DEL removes the specified key. It is not possible with DELto remove keys matching a pattern.

Redis 2.6 introduces an ability to atomically execute Lua scripts using EVAL. This feature can be used to write a version of DEL that accepts wildcard patterns. Below in Ruby flavour, it removes all keys starting with 444:.

require 'redis'

RedisConn = Redis.new
RedisConn.eval(<<-LUA, [], ["441:*"])
local keys = redis.call('keys', ARGV[1])
for i=1,#keys,5000 do
  redis.call('del', unpack(keys, i, math.min(i+4999, #keys)))
end
return keys
LUA