简体   繁体   中英

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.

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

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('*'))
);
$bash = 'redis-cli --scan --pattern "' . $path . '*" | xargs -L 1000 redis-cli DEL';

$res = @shell_exec($bash);

I just use

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

It's works fine for me.

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);

With Predis , I do it like this:

    public function delete($key) {
        $keys = $this->client->keys($key);
        foreach ($keys as $key) {
            $this->client->del($key);
        }
    }

There is no wildcard for delete function . workaround as follows,

// returns total number of keys deleted
function delete($key) {
    if (empty($key)) {  // empty key can delete all
      return false;
    }
    $keys = $redis->keys("$key*");  // keys() function returns array of key strings. `*` wild card pattern can be changed as per need
    if(!$keys) {
        return 0;
    }
    $prefix = $redis->getOption(\Redis::OPT_PREFIX); // keys already have prefix, so we clear until delete finish.
    $redis->setOption(\Redis::OPT_PREFIX, '');
    $count = $redis->del($keys);  // del() function delete array of keys and returns number of keys deleted.
    $redis->setOption(\Redis::OPT_PREFIX, $prefix);

    return $count;
}

Note: As @Akash Gangrade commented, keys() not advised to use due to performance. you can consider Tags based cache invalidation like https://symfony.com/doc/current/components/cache/cache_invalidation.html#tag-aware-adapters

# The keys set in redis
/*
1) "review/itemA/5"
2) "review/itemA/2"
3) "review/itemA/3"
4) "review/itemA/1"
5) "review/itemA/4"
*/

/**
 * Vars for scan
 */
$i = null;
$result = [];

/**
 * Scan redis using desired pattern
 */
while ($result != 0) {
    $result = $redis->scan($i, 'review/itemA/*');
    if (!empty($result)) {
        $all_keys[] = $result;
    }
}

# Use call_user_func_array to flatten multidimensional array into indexed array
## Scan may return duplicate keys, so use array_unique
$unlink_keys = array_unique(call_user_func_array('array_merge', $all_keys));

# As of Redis 4.0 use unlink instead of del to stop blocking
$redis->unlink($unlink_keys);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM