Search code examples
cachingredisredis-cli

How to delete all keys in Redis matching pattern from within redis-cli repl?


I am trying to delete a bunch of keys matching a prefix using redis-cli.

I have been researching how to do this online and the most common suggestion I have seen is to do it straight from the command line, like this:

$ redis-cli [options] KEYS "prefix:*" | xargs redis-cli [options] DEL

However, I would prefer to do this inside the redis-cli tool so that I do not have to pass the hostname, port, and auth parameters in the cli command every time I want to delete keys that match a pattern. So far I have tried:

  • DEL "prefix:*"
  • DEL KEYS prefix:*
  • DEL KEYS "prefix:*"
  • KEYS "prefix:*" | DEL
  • KEYS "prefix:*" DEL

Is there a way to delete all keys under a prefix from within the redis-cli tool? Is the command line the only way to achieve this?

Feel free to comment if you would like me to clarify more.


Solution

  • Run this command inside redis-cli :

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

    Replace prefix:* with your required pattern. The output will be the number of keys deleted.