Find keys matching a pattern without KEYS and delete them safely (SCAN + UNLINK)
RedisMaintenanceCommand
# Cursor-based scan instead of KEYS (call again with the returned cursor until it returns 0):
SCAN 0 MATCH oturum:* COUNT 1000 TYPE string
# Number of keys matching the pattern:
redis-cli -h redis1 -p 6379 --scan --pattern 'oturum:*' --count 1000 | wc -l
# Bulk delete in batches of 500, freeing memory in the background:
redis-cli -h redis1 -p 6379 --scan --pattern 'oturum:*' --count 1000 | xargs -r -n 500 redis-cli -h redis1 -p 6379 UNLINKWhat it does
Scans the keyspace with a cursor without blocking the server, counts keys matching a pattern and type, and bulk deletes them with UNLINK, freeing memory in the background.
When to use it
When cleaning up keys left by an old application version, finding out how many keys exist under a prefix, or when KEYS would otherwise be needed in production.
Caution
KEYS returns the whole keyspace at once and blocks the server for seconds on large data; do not use it in production. SCAN gives no full guarantee for keys added/removed during the scan and may return the same key more than once. Key names containing spaces or quotes break with xargs. Check the count and a few samples before deleting; there is no undo.