How to delete keys by pattern?

To delete keys by pattern in Redis, you can use the SCAN command in combination with the DEL command. Redis does not provide a direct command to delete keys by pattern, but you can achieve this with a script. Here’s an example using the Redis CLI:

  1. First, use the SCAN command to find keys matching a specific pattern. For example, to find keys that start with "prefix:*":
SCAN 0 MATCH prefix:* COUNT 100
  1. Then, you can use the output from the SCAN command to delete those keys. Here’s a simple example using a loop in a shell script:
#!/bin/bash

# Pattern to match
PATTERN="prefix:*"

# Loop through keys matching the pattern
while true; do
    # Get keys matching the pattern
    KEYS=$(redis-cli SCAN 0 MATCH $PATTERN COUNT 100 | tail -n +2)

    # If no keys found, break the loop
    if [ -z "$KEYS" ]; then
        break
    fi

    # Delete the keys
    redis-cli DEL $KEYS
done

This script will continuously scan for keys matching the specified pattern and delete them until no more matching keys are found. Make sure to adjust the pattern as needed.

0 Comments

no data
Be the first to share your comment!