Bulk Deleting Keys in Redis Using Wildcards
Be Cautious with the KEYS Command in Production: Commands like KEYS, FLUSHALL, and FLUSHDB can block Redis when working with large datasets. They may scan the entire keyspace, potentially locking up Redis and degrading performance.
Redis currently does not support bulk deletion of keys using wildcards. However, we can achieve this using the del
command in combination with Linux pipes and the xargs
command.
The del
command in Redis allows you to delete one or more specified keys and returns the number of keys that were deleted. For example, the command del key1 key2 key3
would delete those specific keys.
To delete all keys that start with WxMpSessionKey
, you can use the following command:
1 | [redis@iztz9ploifbvce ~]# redis-cli -h 192.168.182.227 -p 1379 keys "WxMpSessionKey*" | xargs redis-cli -h 192.168.182.227 -p 1379 del |
If you’re connecting to Redis at 127.0.0.1
on the default port 6379
, the command can be simplified to:
1 | redis-cli keys "WxMpSessionKey*" | xargs redis-cli del |