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:

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.


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