Redis: How to delete keys matching a patternPosted by Stanislav Furman on April 10, 2014
Sometimes you might want to purge a set of similar Redis keys in one shot. So far, standard Redis "DEL" command does not allow to remove keys using patterns. However, there is a trick to do this action. Execute the following command in bash:
redis-cli -h [host] -p [port] KEYS "prefix:*" | xargs redis-cli DEL
Seems clear? Wait a minute! What if you use multiple databases (keyspaces) and need to remove keys from a database different from default (0) one? No problem there! Here is the solution:
redis-cli -h [host] -p [port] -n [db] KEYS "prefix:*" | xargs redis-cli -n [db] DEL
Also, for those who's looking for a tool to manage data in Redis there is Redis Desktop Manager. It's still limited in functionality but hopefully will become a very handy tool pretty soon.
There is a little bit more complex but more safe solution (according to Itamar) based on Bash scripting and using redis SCAN: https://gist.github.com/itamarhaber/11126830
If you have questions, don't hesitate to leave them in comments.
Thanks for your comment.
I wouldn't use "and will" because it's too strong. It would depend on the number of keys in the database. I've used it with hundreds and thousands keys with no problem.
Anyway, I would appreciate if you give me your example.
Sorry for the use of strong language, but KEYS is evil :) Its use discouraged in Redis' own documentation (see http://redis.io/commands/keys) and I've seen many users get burnt by misusing/misunderstanding its purpose (i.e. development only).
As bash is your poison of choice (;P), please see https://gist.github.com/itamarhaber/11126830 for a crude, but working, example of using SCAN to delete keys politely.
P.S. looks like there's a small typo in your example above - should be 'port' instead of 'post'
I've corrected the typo. Thanks for your feedback!. ;)
Also updated the article and put the link to the solution that you referred to.
Leave your comment