redis

How to atomically delete keys matching a pattern using Redis


In my Redis DB I have a number of prefix:<numeric_id> hashes.

Sometimes I want to purge them all automatically. How do I do this without using some distributed locking mechanism?


Solution

  • Starting with redis 2.6.0, you can run lua scripts, which execute atomically. I have never written one, but I think it would look something like this

    EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 prefix:[YOUR_PREFIX e.g delete_me_*]
    

    Warning: As the Redis document says, because of performance maters, keys command should not use for regular operations in production, this command is intended for debugging and special operations. read more

    See the EVAL documentation.