Monday, January 26, 2015

Shell script to delete redis keys matching a pattern


A quick way to delete redis keys from the command line would be:
        redis-cli DEL "del_key"

If you wish to delete all keys matching a certain pattern,
        redis-cli KEYS "*del_pattern*" | xargs redis-cli DEL

A more easy shell script for it would be:

#!/bin/sh
[ "$#" -eq 1 ] || { echo "ERROR:1 argument required, $# provided"; exit 1; }
redis-cli KEYS "*$1*" | xargs redis-cli DEL
view raw redis-delete.sh hosted with ❤ by GitHub
Save it as redis-delete.sh and you can just run it as:
        ./redis-delete.sh del_pattern

UPDATE:
The above code using KEYS does not scale well and so for a more performance efficient code, we can use SCAN which is a cursor-based iterator.

#!/bin/sh
[ "$#" -eq 1 ] || { echo "ERROR:1 argument required, $# provided"; exit 1; }
cursor=-1
keys=""
while [ $cursor -ne 0]; do
if [ $cursor -eq -1 ] then
cursor=0
fi
reply=`redis-cli SCAN $cursor MATCH $1`
cursor=`expr "$reply" : '\([0-9]*[0-9 ]\)'`
keys=${reply#[0-9]*[[:space:]]}
redis-cli DEL $keys
done

4 comments:

  1. Just note that `KEYS` can potentially run for a long time and consume a significant amount of RAM while Redis prepares the reply. An alternative and safer approach is using `SCAN` - see here for a sample script that uses it: http://stackoverflow.com/a/23399125/3160475

    ReplyDelete
    Replies
    1. Thanks for the info. Learnt a new thing. I have added an update above using SCAN.

      Delete
  2. I need to add space and ; to rhe code when I used it

    while [ $cursor -ne 0 ]; do
    if [ $cursor -eq -1 ]; then
    cursor=0
    fi

    ReplyDelete