I am trying to delete multiple keys from my remote Redis db using the following command.
redis-cli -h <host> -p 6379 KEYS "myprefix:*" | xargs redis-cli -h <host> -p 6379 DEL
It has deleted all the matching keys except the ones having spaces in them.
For e.g.
Deleted:
Not deleted:
What should be my query pattern so that these get deleted too? I tried googling but was unable to find any solution.
Redis does not offer a way to bulk delete keys. You can however use redis-cli and a little bit of command line magic to bulk delete keys without blocking redis. This command will delete all keys matching users:* If you are in redis 4.0 or above, you can use the unlink command instead to delete keys in the background.
In Redis 4.0, there is a new command UNLINK to delete the keys in Redis memory. This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not exist. However the command performs the actual memory reclaiming in a different thread, so it is not blocking, while DEL is.
To clear data of a DCS Redis 4.0 or 5.0 instance, you can run the FLUSHDB or FLUSHALL command in redis-cli, use the data clearing function on the DCS console, or run the FLUSHDB command on Web CLI. To clear data of a Redis Cluster instance, run the FLUSHDB or FLUSHALL command on every shard of the instance.
To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.
The issue is with xargs, not your KEYS query. If you run your query, you will notice that it correctly returns the keys with spaces in them. The problem is that by default xargs splits the strings piped into it by blanks and newlines. To change this behaviour so that it only delimits by newlines, add the -d "\n" option. For example:
redis-cli -h <host> -p 6379 keys "myprefix:*" | xargs -d "\n" redis-cli -h <host> -p 6379 del
For anyone using Mac OS xargs (BSD) instead of linux (GNU) xargs the following works
redis-cli -h <host> -p 6379 keys "myprefix:*" | xargs -I% redis-cli -h <host> -p 6379 del %
or for other weird characters like speech marks this works
redis-cli -h <host> -p 6379 --scan --pattern "myprefix:*" | tr '\n' '\0' | xargs -0 -I% redis-cli -h <host> -p 6379 del %
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With