Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Redis Keys matching a pattern Laravel 5.7

I have been searching and tried multiple solution but could got any helping results, I want to clear/delete all keys matching pattern products:*.

Following are the things i have tried.

Redis::del('products:*');
Redis::del('*products:*');
Redis::del('*products*');

But nothing worked.

It is deleting key if i provide exact key name like : Redis::del('products:2:3:45');

Key are being generated like this: products:1:4:45

I have read documentation but could find anything regarding my query.

Please help.

like image 816
Noman Ali Avatar asked Oct 22 '19 14:10

Noman Ali


3 Answers

You can't delete by pattern. But you can get all the keys by this pattern and then delete them:

Redis::del(Redis::keys('products:*'));

See more here.

like image 175
freeek Avatar answered Nov 18 '22 05:11

freeek


I read somewhere that you cannot delete based on wildcard, you need to give the keys explicitly.

There is still a way to grab all keys and then run delete on those keys. I do it using cli like this:

redis-cli KEYS "products:*" | xargs redis-cli DEL

It fetches all the keys that match the query and run DEL on them. You can execute this command from Laravel.

In Laravel, fetch all keys and run delete on them using

Redis::del(Redis::keys('products:*'));
like image 38
Danyal Sandeelo Avatar answered Nov 18 '22 06:11

Danyal Sandeelo


With Laravel 8 it wasn't deleting cause the key has a prefix so what I did is remove the prefix before passing it to del()

$keys = Redis::keys( 'products:*' );

if ( !empty( $keys ) ){
    $keys = array_map(function ($k){
        return str_replace('_prefix_database', '', $k);
    }, $keys);

    Redis::del( $keys );
}

i hope this will be helpful for someone

like image 2
Moode Osman Avatar answered Nov 18 '22 06:11

Moode Osman