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

久未见 提交于 2019-12-10 16:29:28

问题


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.


回答1:


I just use

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

It's works fine for me.




回答2:


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




回答3:


$bash = 'redis-cli --scan --pattern "' . $path . '*" | xargs -L 1000 redis-cli DEL';

$res = @shell_exec($bash);



回答4:


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('*'))
);



回答5:


With Predis, I do it like this:

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



回答6:


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


来源:https://stackoverflow.com/questions/32295488/how-to-delete-multiple-redis-keys-with-the-same-pattern-in-php-using-phpredis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!