6

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.

Graham S.
  • 1,480
  • 1
  • 20
  • 28

2 Answers2

9

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.

Aswin Sanakan
  • 655
  • 8
  • 10
2

You can write a lua script to delete keys.

local matches = redis.call('KEYS', ARGV[1])

local result = 0
for _,key in ipairs(matches) do
    result = result + redis.call('DEL', key)
end

return result 

Save this file locally as delete.lua and run it like so:

$redis-cli script load "$(cat delete.lua)"

"efe4f6a74ff9baba16d039f892dd09174b9f5777"

That "$(cat delete.lua)" just turns our script into a quoted argument. The important bit is the number that comes back (its in hex). It's the SHA1 signature of the script. We can use this to invoke the script using the EVALSHA command inside redis-cli like this:

EVALSHA efe4f6a74ff9baba16d039f892dd09174b9f5777 1 nil prefix:*
Monzurul Shimul
  • 8,132
  • 2
  • 28
  • 42