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
Scripting
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.
Written by Justin Poliey
Related protips
6 Responses
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.;)
Thanks @davidann. btw I already had a note in the tip :)
Dah, totally right. Overlooked it. sorry.:)
For those keys that have space:
redis-cli --raw keys "$PATTERN" | sed 's/.*/"&"/' | xargs redis-cli del
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.
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: