latest

Redis: Delete all keys LIKE

Sometimes in Redis you want to delete a mass of keys that were created accidentally, there are too many to clear out one by one and FLUSHDB is certainly out of the question.

For those of you who are more familiar with the SQL family, MySQL for instance, you may occasionally use the "LIKE" keyword. Such as in the case of...

DELETE FROM users WHERE email LIKE '%@spam-domain.biz'

Well you can get the same functionality in Redis straight from your command-line...

redis-cli KEYS "users.email.*@spam-domain.biz" | xargs redis-cli DEL

The official documentation has this to say about the KEYS keyword:

Returns all keys matching pattern. While the time complexity for this operation is O(N), the constant times are fairly low. For example, Redis running on an entry level laptop can scan a 1 million key database in 40 milliseconds.

Keep reading if you want an explanation of how and why it works.


redis-cli - here we are just invoking the redis command line interface

KEYS - we tell Redis to return all KEYS that match the next arguement

"users.email.*@spam-domain.biz" We only want keys that start with 'users.email.' and end with '@spam-domain.biz', the * symbol acts as a wild card in Redis and is the same as saying 'anything and everything can be where this star is, I don't care'

| - this is the 'pipe' function, it lets the command line know that you want to capture whatever the result of the command before it was and send it to the command ahead of it

xargs - accepts whatever | sent it and turns it into arguements for the next command

redis-cli DEL - once again we are invoking the redis command line interface, this time calling the DEL (delete) command. Since we passed the list of things we don't want through xargs it means that list will be used to know what to delete

Author image
Washington, USA