To bulk delete specified keys, use the Redis UNLINK command together with the Linux cat and xargs commands. To bulk delete keys that match a pattern, use the Redis SCAN and UNLINK commands.
Notes
Back up your data before deleting keys, and perform deletions during off-peak hours.
Run the examples in this topic from a client such as redis-cli or a Python client on an ECS instance or a local machine. You cannot run these examples in DMS.
Bulk delete specified keys
Before running the command, write the list of keys to delete to a file.
The following command reads each line from the specified file as a Redis key, connects to the Redis server using redis-cli, and deletes the keys using the UNLINK command.
# Use the asynchronous UNLINK command (Redis 4.0+) to avoid blocking. If your Redis version is earlier than 4.0, replace UNLINK with DEL.
cat <file> | xargs redis-cli -h <host> -p <port> -a <password> UNLINKThe Linux xargs command breaks long parameter lists into smaller segments to pass to other commands. This avoids errors caused by overly long argument lists and can be used alone or with other commands via pipes and redirection operators.
Parameter description:
file: The path of the file containing the keys to delete. For example, key.txt.
host: The endpoint of the Redis instance. For more information, see View endpoints.
port: The port number of the Redis instance. The default value is 6379.
password: The password of the Redis instance. For more information, see Logon methods.
Example:
cat key.txt | xargs redis-cli -h r-bp127cu5tb*****.redis.rds.aliyuncs.com -a Test**** UNLINKBulk delete keys that match a pattern
Method | Scenarios |
(Recommended) Fuzzy delete with SCAN and UNLINK | Safely delete large amounts of data in a production environment. This method is non-blocking and ensures the stability of your online services. |
High-throughput fuzzy delete in Pipeline mode | Maximize throughput and reduce network latency by submitting many commands in a single batch. This method is ideal for scenarios that require maximum deletion efficiency. |
Fuzzy delete with KEYS and DEL | Delete small amounts of data in development or staging environments, or during a complete service outage. The KEYS command blocks the server and is extremely risky to use in a production environment. |
(Recommended) Fuzzy delete with SCAN and UNLINK
This method iteratively scans for and deletes keys that match a pattern. The following is a Python code sample:
import redis
import sys
def main(argv):
if len(argv) < 4:
print("Usage: python scan_and_del.py host port password match")
sys.exit(-1)
host = argv[1]
port = argv[2]
password = argv[3]
match = argv[4]
print("host: %s, port: %s, password: %s, match: %s\n" % (host, port, password, match))
redis_cli = redis.StrictRedis(host=host, port=port, password=password)
cursor = 0
rnd = 1
while rnd == 1 or cursor != 0:
result = redis_cli.scan(cursor=cursor, match=match, count=1000)
ret_cursor = result[0]
ret_keys = result[1]
num_keys = len(ret_keys)
print("Deleted %d keys in round %d, cursor: %d" % (num_keys, rnd, ret_cursor))
if 0 != num_keys:
ret_unlink = redis_cli.unlink(*ret_keys)
print("unlink returned: %d, keys unlinked: %s" % (ret_unlink, ret_keys))
cursor = ret_cursor
rnd += 1
print("")
if __name__ == '__main__':
main(sys.argv)Call the scan_and_unlink.py sample code, specifying the connection information for the Redis instance and the key matching pattern, to delete keys based on a fuzzy match.
python scan_and_unlink.py <host> <port> <password> "<key>" Parameter description:
host: The endpoint of the Redis instance. For more information, see View endpoints.
port: The port number of the Redis instance. The default value is 6379.
password: The password of the Redis instance. For more information, see Logon methods.
key: The pattern to match keys in a database. For example,
"test*"matches keys that have the test prefix, such astest1,test2, andtest3.For more information about wildcard character matching:
w?rld: Matches a five-character string that starts with w and ends with rld, such as world, warld, and wxrld.
w*rld: Matches any string that starts with w and ends with rld, such as wrld and woooorld.
w[ae]rld: Matches warld and werld, but not world.
w[^e]rld: Matches world and warld, but not werld.
w[a-b]rld: Matches warld and wbrld.
High-throughput fuzzy delete in Pipeline mode
This method iteratively scans for keys that match a pattern and then uses a pipeline to send UNLINK commands in a batch. This approach significantly reduces network round trip time (RTT). The following is a Python code sample:
import redis
import sys
def main(argv):
if len(argv) < 4:
print("Usage: python scan_and_del_pipeline.py host port password match")
sys.exit(-1)
host = argv[1]
port = int(argv[2]) # Convert port to integer
password = argv[3]
match = argv[4]
print(f"host: {host}, port: {port}, password: {'*' * len(password)}, match: {match}\n")
# After accumulating 1000 keys, submit a DEL command through the pipeline. You can adjust this number as needed.
pipeline_batch_size = 1000
redis_cli = redis.StrictRedis(host=host, port=port, password=password, decode_responses=True)
cursor = 0
total_deleted_count = 0
keys_to_delete = []
print("Starting key scan...")
# Use a 'while True' loop and exit when the cursor is 0.
while True:
# 1. Scan a batch of keys.
cursor, keys = redis_cli.scan(cursor=cursor, match=match, count=1000)
if keys:
# 2. Collect the scanned keys into a list for deletion.
keys_to_delete.extend(keys)
# 3. When the deletion list reaches the batch size or the scan is complete, execute the deletion.
if len(keys_to_delete) >= pipeline_batch_size or cursor == 0:
if keys_to_delete:
print(f"Accumulated {len(keys_to_delete)} keys. Preparing to delete via Pipeline...")
# --- Pipeline -----------
pipe = redis_cli.pipeline(transaction=False, shard_hint=None)
pipe.delete(*keys_to_delete)
result = pipe.execute()
# -------------------------
deleted_in_batch = result[0]
total_deleted_count += deleted_in_batch
print(f" -> Pipeline executed. Deleted {deleted_in_batch} keys in this batch.")
# Clear the deletion list to prepare for the next batch.
keys_to_delete = []
# 4. If the scan is complete, exit the loop.
if cursor == 0:
break
print(f"\nScan finished. Total keys deleted: {total_deleted_count}")
if __name__ == '__main__':
main(sys.argv)
Run the preceding scan_and_unlink_pipe.py sample code with the connection information for the Redis instance and a key matching pattern to delete keys based on a fuzzy match.
python scan_and_unlink_pipe.py <host> <port> <password> "<key>" Parameter description:
host: The endpoint of the Redis instance. For more information, see View endpoints.
port: The port number of the Redis instance. The default value is 6379.
password: The password of the Redis instance. For more information, see Logon methods.
key: The pattern to match keys in a database. For example,
"test*"matches keys that have the test prefix, such astest1,test2, andtest3.For more information about wildcard character matching:
w?rld: Matches a five-character string that starts with w and ends with rld, such as world, warld, and wxrld.
w*rld: Matches any string that starts with w and ends with rld, such as wrld and woooorld.
w[ae]rld: Matches warld and werld, but not world.
w[^e]rld: Matches world and warld, but not werld.
w[a-b]rld: Matches warld and wbrld.
Fuzzy delete with KEYS and DEL
Using the KEYS command may cause high CPU usage. Perform this operation during off-peak hours.
Using the KEYS command on a database with many keys can affect performance. Use this command only on databases with a small number of keys.
Run the following command to find all matching keys using the KEYS command with a wildcard pattern and then pipe them to the DEL command for deletion.
redis-cli -h <host> -p <port> -a <password> KEYS "<key>" | xargs redis-cli -h <host> -p <port> -a <password> DELParameter description:
host: The endpoint of the Redis instance. For more information, see View endpoints.
port: The port number of the Redis instance. The default value is 6379.
password: The password of the Redis instance. For more information, see Logon methods.
key: The pattern to match keys in a database. For example,
"test*"matches keys that have the test prefix, such astest1,test2, andtest3.For more information about wildcard character matching:
w?rld: Matches a five-character string that starts with w and ends with rld, such as world, warld, and wxrld.
w*rld: Matches any string that starts with w and ends with rld, such as wrld and woooorld.
w[ae]rld: Matches warld and werld, but not world.
w[^e]rld: Matches world and warld, but not werld.
w[a-b]rld: Matches warld and wbrld.
Example:
redis-cli -h r-bp127cu5tb*****.redis.rds.aliyuncs.com -a Test**** KEYS "keys*" | xargs redis-cli -h r-bp127cu5tb*****.redis.rds.aliyuncs.com -a Test**** DELVerify that the keys are deleted
Run the SCAN command again to confirm that no matching keys are returned.
# Count the number of matching keys. The expected result is 0.
redis-cli -h <host> -p <port> -a <password> --scan --pattern 'test:*' | wc -l