skip to Main Content

we are currently using this command from shell to purge our Redis DB:

redis-cli -h zapi.data.com flushdb

However, now I am being told that I have to delete all keys, except for the key that is "zrtt_industry". How can I do a regular expression that will delete all but the key matching my pattern, that pattern being "zrtt_industry".

Many thanks!

2

Answers


  1. You can do something like this –

    EVAL "local keys = redis.call('keys', '*'); for i=1,#keys do if keys[i] ~= 'zrtt_industry' then redis.call('del', keys[i]) end end" 0
    

    Redis EVAL to run a Lua script that:

    • Gets all keys
    • Iterates through them
    • Deletes each key that doesn’t match ‘zrtt_industry’

    I have tested it and it works for me on the redis-cli

    enter image description here

    So in your case you need to run this,

    redis-cli -h zapi.data.com EVAL "local keys = redis.call('keys', '*'); for i=1,#keys do if keys[i] ~= 'zrtt_industry' then redis.call('del', keys[i]) end end" 0
    
    Login or Signup to reply.
  2. Unfortunately, Redis does not provide a native “negative match” pattern or a built-in command to flush all keys except for a specific one. You must instead retrieve all keys and then filter them out before deleting.

    Approach using a shell pipeline:
    1. List all keys with redis-cli keys "*".
    2. Use grep -v to exclude the key zrtt_industry.
    3. Pass the remaining keys to redis-cli del via xargs.

    For example:

    redis-cli -h zapi.data.com KEYS "*" | grep -v ‘^zrtt_industry$’ | xargs -n 1 redis-cli -h zapi.data.com DEL

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search