Though Redis allows searching entries based on a key pattern (command
KEYS
), it doesn't allow bulk deleting entries based on a key pattern, what can be useful in many scenarios, as that in which you need to refresh part of your cache and don't want to entirely drop it.
However, we can do it by using the
redis-cli
pipe mode, that allows redis-cli
executing a list of commands received by the standard input.
Let's see how to delete a set of entries based on a key pattern:
redis-cli --raw KEYS mykeyprefix* | awk '{print "DEL "$0}' | redis-cli --pipe
As can be seen, three commands are used:
- The first command,
redis-cli --raw KEYS mykeyprefix*
, executes the Redis commandKEYS mykeyprefix*
for getting all the keys starting by "mykeyprefix", and sends the raw result to the standard output. awk '{print "DEL "$0}'
basically transforms the previous command output by prefixing every line withDEL
, so creating a RedisDEL
command for every key matching our pattern.- Finally the last command,
redis-cli --pipe
, executes every command received by the standard input, that is, all theDEL
commands created in the previous step.
Note that for simplifying the example
redis-cli
is using the default hostname (argument -h
, default value 127.0.0.1
) and not setting the password by command line (argument -a
, by default taken from the env variable REDISCLI_AUTH
). If your conditions are not those described, you should set those arguments in the command line.
Also note that, as described in the
KEYS
documentation, it is "a command that should only be used in production environments with extreme care. It may ruin performance when it is executed against large databases".
Comentarios
Publicar un comentario