How to Delete Multiple Redis Keys With the Same Pattern in PHP Using Phpredis

Delete Redis Keys matching a pattern Laravel 5.7

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


See more here.

Remove All Keys from Redis in PHP

If you have the redis connection you can simply do $redis->flushDB(); to delete all keys from the selected database.

Or if you are using laravel framework you could also do Redis::flushDB();

How to atomically delete keys matching a pattern using Redis

Starting with redis 2.6.0, you can run lua scripts, which execute atomically. I have never written one, but I think it would look something like this

EVAL "return'del', unpack('keys', ARGV[1])))" 0 prefix:[YOUR_PREFIX e.g delete_me_*]

Warning: As the Redis document says, because of performance maters, keys
command should not use for regular operations in production, this
command is intended for debugging and special operations. read

See the EVAL documentation.

PHP Predis: how to get/delete keys containing special characters?

Solved. The problem was related to the fact that predis insert automatically a configured prefix at the beginning of each key (in my case 'vir3_data_cache') before doing any operation. But the keys("*") command does not strip off the prefix from the key.

So I need to do the following in order to make my code work:

$prefix = $this->redis->getOptions()->__get('prefix')->getPrefix();

$keys = $this->redis->keys("*");
$removed = 0;
foreach ($keys as $key) {
if (substr($key, 0, strlen($prefix)) == $prefix) {
$key = substr($key, strlen($prefix));

Select all key data for a specific pattern from Redis using PHP

The simplest route to SET you can take for a better performance is to PIPE the keys and hit the redis server once to execute all of them instead of a trip/key .

$pipeline = $redis->multi($host, Redis::PIPELINE);

//put result in our shared list
foreach ($items as $item) {
$pipeline->sAdd($key, $item);

$ret = $pipeline->exec();

At the same time, there is also libraries out there if you are seeking a different way to trasnlate commands to Redis Protocol .

redis bulk import using --pipe

Related Topics

Leave a reply