Redis cli delete multiple keys
Asked Answered
C

8

12

I have installed Redis in centos and I have multiple keys of redis like this,

Product:<id>:<url>

How can I delete all Product:*:* with CLI ?

Redis version : 3.2.4 [ Latest I guess ]

Thanks!

Catchword answered 18/11, 2016 at 13:12 Comment(1)
Possible duplicate of How to atomically delete keys matching a pattern using RedisTauro
C
38

Using the redis-cli tool, you can do the following:

redis-cli --scan --pattern 'Product:*:*' | xargs redis-cli DEL
Corpuz answered 18/11, 2016 at 16:32 Comment(8)
Not too sure why that failed for me but switched to this and it worked: redis-cli keys '*' | grep Product | xargs -i redis-cli del {}Razor
@Razor "failed" how?Corpuz
My bad @Itamar. Just realized I'd typed a wrong pattern face palm All is well. Thanks for the tip! UpvotedRazor
No problem, I had to undergo cosmetic surgery to remove the impression of my palm from my face <- so many years doing it :)Corpuz
it sounds good but if you have more than one db or thousands or millions of keys I released my searches result below as answerTribesman
You can also chose server with -u and database with -n parameter like redis-cli -u redis://redisserver:6379 -n 1 --scan --pattern 'Product:*:*''Haycock
I am getting (error) CROSSSLOT Keys in request don't hash to the same slot I am using following to delete pattern hi* form cluster redis-cli -u redis://localhost:6379 --scan --pattern 'hi*' | xargs redis-cli -u redis://localhost:6379 DELMiguelmiguela
I need to use xargs -L 1 else it won't resolve the each line key result.Dissect
R
12

Starting with redis 2.6.0, you can use LUA scripts.

You should use this variant over the SCAN | XARGS variant because it's much faster.

The following script works also for a large amount of keys.

  1. open your redis-cli
redis-cli -p somePort -a somePassword
  1. Replace somePattern with your pattern e.g. *cars* (remember it's not regex)
EVAL "for _,k in ipairs(redis.call('keys','somePattern')) do redis.call('del',k) end" 0
Ripple answered 23/12, 2020 at 16:54 Comment(0)
M
6

There's no built-in command for that. You have to use the SCAN command to get all keys that match the pattern, then use the DEL command to remove these keys.

// scan from cursor 0 to get the next cursor and keys
SCAN 0 match Product:*:*
// next_cursor, Product:x1:y1, Product:x2:y2, ...
DEL Product:x1:y1 Product:x2:y2 ...
// scan from the next cursor until it return 0
SCAN next_cursor match Product:*:*

Another solution is to use a HASH to save keys of this pattern:

// set key value
HSET Products Product:<id>:<url> value
// remove a single key
HDEL Products Product:<id>:<url>
// remove all keys
DEL Products
Mattern answered 18/11, 2016 at 13:27 Comment(2)
Can you give me example to scan and then delete ?Catchword
@JohnFG I update the answer. For more details on SCAN, check the documentation.Mattern
S
3
-n <db>            Database number

shell: redis-cli -n 1 --scan --pattern prefix:* | xargs redis-cli -n 1 del

Slew answered 29/5, 2019 at 10:7 Comment(0)
B
2

put all keys you want to delete inside keylist.txt file then:

cat keylist.txt | while read rediskey; do echo "Deleting $rediskey" && redis-cli -c -h 'hostname' -p XXXX -a 'XXXXXX' UNLINK $rediskey; done
Brade answered 29/1, 2021 at 11:52 Comment(0)
A
0

There are several ways to do that.

  1. https://gist.github.com/ddre54/0a4751676272e0da8186 Is not recommended on production server since it is using KEYS keyword
  2. Using ioredis (https://github.com/luin/ioredis#streamify-scanning) which supports Redis >= 2.6.12 and (Node.js >= 6)

If you want to follow second example just do following steps:

  1. Install node js >=6
  2. Create folder and inside it install ioredis by running following command:

    npm install ioredis

  3. Inside that folder create redis.js file with following content

    module.exports.redisDel = function(key) {
    console.log("del started for key: ", key);
    var Redis = require("ioredis");
    
    var redis = new Redis({
        port: 6379, // Redis port
        host: "192.168.93.27", // Redis host
        family: 4, // 4 (IPv4) or 6 (IPv6)
        password: "SetCorrectPassword"
    });
    
    return new Promise((resolve, reject) => {
    
        var stream = redis.scanStream({
            // only returns keys following the pattern of "key"
            match: key,
            // returns approximately 100 elements per call
            count: 100
        });
    
        stream.on('data', function (resultKeys) {
            if (resultKeys.length) {
                console.log(resultKeys)
                redis.del(resultKeys); //from version 4 use unlink instead of del
            }
            else {
                console.log("nothing found");
            }
        });
        stream.on('end', function (resultKeys) {
            console.log("end");
            resolve()
        })
    })
    

    }

  4. Run script by passing desired key (in our case yourKey*)

node -e 'require(\"./redis\").redisDel(\"yourKey*\")'

Aesthete answered 3/9, 2019 at 15:24 Comment(0)
K
0

For Windows cmd.exe command interpreter, use FOR with /F:

FOR /F %I IN ('redis-cli KEYS Product:*:*') DO redis-cli DEL %I

If you have backquote commands enabled (not likely) you might need to use backquotes instead of apostrophes.

Source: FOR /?

Kronstadt answered 27/1, 2023 at 20:33 Comment(0)
L
-1

The answer suggested above by Itamar works perfectly.

but in case you need to provide authentication in your redis setup when deleting and need to select the host in which to run the del command, you can add password, port and host as follows:-

redis-cli -a {password} --scan --pattern "*{your pattern}*"  -h {hostip} -p {port}| xargs redis-cli -a {password} -h {hostip} -p {port} del

This solved my issue, hope its useful for you as well..

Liftoff answered 12/10, 2023 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.