Redis: Delete keys matching a pattern
Ilhan Ates

Ilhan Ates / November 08, 2022

1 min read––– views

A way to bulk delete keys is not offered in Redis. However, it can be achieved with a single line using redis-cli and xargs.

redis-cli --scan --pattern <pattern> | xargs redis-cli unlink

Or if you are on Redis 4.0 and below:

redis-cli --scan --pattern <pattern> | xargs redis-cli del

unlink allows non-blocking deletion of keys, which can be useful in production.

How does it work?

  1. redis-cli --scan --pattern <pattern> returns every key matching the pattern, without blocking the redis instance.
  2. The result is then piped onto xargs, which combines the lines and essentially runs redis-cli unlink <key1> <key2>....
  3. If there are too many keys matching the pattern, xargs accounts for it and runs unlink multiple times.