Introducing Redis Overflow - Build Stackoverflow API's using node.js and Redis.

How to Delete Keys Matching a Pattern in Redis

Redis does not offer a way to bulk delete keys. You can however use redis-cli and a little bit of command line magic to bulk delete keys without blocking redis.


This command will delete all keys matching users:*
redis-cli --scan --pattern users:* | xargs redis-cli del

If you are in redis 4.0 or above, you can use the unlink command instead to delete keys in the background.


redis-cli --scan --pattern users:* | xargs redis-cli unlink

How does the Script Work?

  1. First, we use redis-cli --scan --pattern <pattern> to get a list of keys, one key per line. Since this uses scan, redis server is not blocked.
  2. xargs takes multiple lines and combines them on the same line, so you are essentially running the command del <key1> <key2>...
  3. If you have thousands of keys that match the pattern, xargs will automatically execute redis-cli multiple times.

See Also