9

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.

Noman Ali
  • 3,160
  • 10
  • 43
  • 77
  • See https://stackoverflow.com/questions/32295488/how-to-delete-multiple-redis-keys-with-the-same-pattern-in-php-using-phpredis. This may solve your problem – Ali Khalili Oct 22 '19 at 14:09

5 Answers5

23

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.

freeek
  • 985
  • 7
  • 22
4

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:*'));
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
3

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

Moode Osman
  • 1,715
  • 18
  • 17
0

We can use the array_map function to go over all the keys in redis and do delete.

$redis = new Redis;
$prefix = $redis->getOption(Redis::OPT_PREFIX);
$redis->delete(array_map(
    function ($key) use ($prefix) {
        return str_replace($prefix, '', $key);
    }, $redis->keys('*'))
);
Nick
  • 536
  • 2
  • 8
0

With Laravel8 I use:

    public function handle()
    {
        $this->call('queue:flush');

        $arrayFailed        = Redis::connection('horizon')->keys('failed:*');
        $arrayFailedJobs    = Redis::connection('horizon')->keys('failed_jobs');
        $arrayToRemove      = array_merge($arrayFailed, $arrayFailedJobs);

        $arrayMap = array_map(function ($k) {
            return str_replace(config('horizon.prefix'), '', $k);
        }, $arrayToRemove);
        Redis::connection('horizon')->del($arrayMap);

        $this->line('');
    }
vlauciani
  • 1,010
  • 2
  • 13
  • 27