Redis: How to delete keys matching a pattern

Posted 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.

UPDATE:

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.


Comments

Itamar Haber says:
April 20, 2014 at 09:44 am
This approach is quite dangerous as KEYS can (and will) result in a DoS. While this may be a no biggie in dev/test env, production is another matter... Redis' SCAN is a better way to do it.
Flag as SPAM  |  Permalink
Stan says:
April 20, 2014 at 05:12 pm
Hi Itamar,

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.

Flag as SPAM  |  Permalink
Itamar Haber says:
April 20, 2014 at 10:30 pm
Hi Stan,

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.

Cheers,
Itamar

P.S. looks like there's a small typo in your example above - should be 'port' instead of 'post'
Flag as SPAM  |  Permalink
Stan says:
April 21, 2014 at 05:01 pm
Hi Itamar,

I've corrected the typo. Thanks for your feedback!. ;)
Also updated the article and put the link to the solution that you referred to.

Much appreciated!
Flag as SPAM  |  Permalink

Leave your comment

Fields with * are required.

* When you submit a comment, you agree with Terms and Conditions of Use.