Last Updated: February 25, 2016
· jdp

Quickly move and delete Redis keys by pattern

When debugging code that uses Redis, it's usually really useful to be able to delete keys by pattern, like a bunch of keys that match a common prefix. It's also useful to be able to keep only some keys that match a certain pattern, and then delete the rest. It's easy to do right from the command line with the redis-cli program.

The pattern should follow the same pattern used by the KEYS command. It's a good idea to read the notes here: KEYS is an expensive command, and it should be used with some caution.

Delete All Keys Matching Pattern

Here's how you can quickly delete all keys that match a certain pattern $PATTERN. It uses the DEL command, so many keys are deleted in a single command.

$ redis-cli --raw keys "$PATTERN" | xargs redis-cli del

Move All Keys Matching Pattern

Here's how you move all keys matching $PATTERN from db0 to db1. It uses the MOVE command, so only 1 key can be moved per command. This doesn't mean you'll have to call this multiple times, it just means that it'll make more network round-trips.

$ redis-cli --raw keys "$PATTERN" | xargs -L1 -I{} redis-cli move {} 1

Now you can safely flush db0, and all the keys you saved will still available in db1. After you flush db0, you can move the keys back to db0 from db1 again:

$ redis-cli flushdb
$ redis-cli --raw -n 1 keys "$PATTERN" | xargs -L1 -I{} redis-cli move {} 0


I use these commands all the time, so I wrote some little shell scripts whose command options match the redis-cli invocation to make this easier to do, especially with remote hosts. They're available as redis-delkeys.sh and redis-movekeys.sh.

6 Responses
Add your response


Nice tip, it's informative!

It might be a good idea to have a reminder that the keys call is pretty expensive so it is dangerous to use it in production.;)

over 1 year ago ·

Thanks @davidann. btw I already had a note in the tip :)

over 1 year ago ·

Dah, totally right. Overlooked it. sorry.:)

over 1 year ago ·

For those keys that have space:
redis-cli --raw keys "$PATTERN" | sed 's/.*/"&"/' | xargs redis-cli del

over 1 year ago ·

Consider using SCAN (http://redis.io/commands/scan) instead of KEYS in production - e.g. SCAN 0 MATCH {pattern} and then iterate over the results.

over 1 year ago ·

I just published a command line interface utility to npm and github that allows you to delete keys that match a given pattern (even *) from a Redis database.

You can find the utility here:


over 1 year ago ·
Filed Under