In redis, how do i remove keys?

前端 未结 8 2086
遥遥无期
遥遥无期 2020-12-13 07:56

I want to remove keys that match \"user*\".

how do I do that in redis command line?

相关标签:
8条回答
  • 2020-12-13 08:28

    Further to orangeoctopus' answer, you don't need the echo and pipe, you can pass commands as arguments into redis-cli. This means you can do

    for key in `redis-cli "KEYS" "user*" | awk '{print $1}'`
     do redis-cli "DEL" "$key"
    done
    
    0 讨论(0)
  • 2020-12-13 08:29

    Now there is a command to remove a key,i.e., DEL key [keys]

    DEL key...

    0 讨论(0)
  • 2020-12-13 08:29

    When using the oneliner, you can edit the pattern in case it escapes specific characters. For instance, to delete patterns like '\b test \b' use:

    redis-cli --raw KEYS '\\b*' | sed 's/\\b/\\\\b/g' | xargs redis-cli del
    
    0 讨论(0)
  • 2020-12-13 08:37

    This is not a feature right now to be able to do in one shot (see the comments in the DEL documentation). Unfortunately, you are only left with using KEYS, looping through the results, and then using DEL to remove each one.

    How about using bash a bit to help?

    for key in `echo 'KEYS user*' | redis-cli | awk '{print $1}'`
     do echo DEL $key
    done | redis-cli
    

    To step through it:

    1. echo 'KEYS user*' | redis-cli | awk '{print $1}' -- get all the keys and strip out the extra text you don't want with awk.
    2. echo DEL $key -- for each one, create an echo statement to remove it.
    3. | redis-cli -- take the DEL statements and pass them back into the cli.

    Not suggesting this is the best approach (you might have some issues if some of your usernames have spaces in them, but hopefully you get the point).

    0 讨论(0)
  • 2020-12-13 08:38

    Use this to remove redis keys having backslashes, quotes, double quotes or spaces:

    redis-cli KEYS "user*" | sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | sed "s/'/\\\\'/g" | sed 's/ /\\ /g' | xargs redis-cli DEL

    0 讨论(0)
  • 2020-12-13 08:38

    I know this is old, but for those of you coming here form Google:

    I just published a command line interface utility to npm and github that allows you to delete keys that match a given pattern (even , or as you asked user) from a Redis database.

    You can find the utility here:

    https://www.npmjs.com/package/redis-utils-cli

    0 讨论(0)
提交回复
热议问题