Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple redis keys with the same pattern in PHP using phpredis?

By using phpredis, I have saved some data in pagination like this:

   review/itemA/1
   review/itemA/2 

where 1 and 2 are page numbers. I read in the document that you can use wildcards to retrieve multiple keys.

$allKeys = $redis->keys('*');   // all keys will match this.
$keyWithUserPrefix = $redis->keys('user*');

But can I delete all the old keys using wildcards as well when someone has posted a new review? Can I do something like:

$redis->delete('review/itemA/*'); // or  $redis->delete('review/itemA*')

It didn't work however.

like image 775
RedGiant Avatar asked Aug 30 '15 10:08

RedGiant


4 Answers

No - Redis' DELlete does not accept wildcards, you have to name the keys explicitly. See here for possible directions: https://stackoverflow.com/a/23399125/3160475

like image 88
Itamar Haber Avatar answered Oct 25 '22 00:10

Itamar Haber


When using phpredis, you can get the prefix (which phpredis automatically prepends everywhere) and delete a pattern of keys that way :

<?php
...

$prefix = $redisClient->getOption(Redis::OPT_PREFIX);
$redisClient->delete(array_map(
    function ($key) use ($prefix) {
        return str_replace($prefix, '', $key);
    }, $redisClient->keys('*'))
);
like image 29
KevinS Avatar answered Oct 25 '22 01:10

KevinS


I just use

$redis->delete($redis->keys('*'));

It's works fine for me.

like image 29
Akuma Avatar answered Oct 25 '22 01:10

Akuma


Predis (->del) allows to pass a keys array too.
It works here and is faster than the del inside the foreach.

$prefix = $this->client->getOptions($this->OPT_PREFIX);
$keys = $this->client->keys("$key*");
if ($keys) $this->client->del($keys);
like image 23
user10319207 Avatar answered Oct 25 '22 00:10

user10319207