How to use SCAN with MATCH option in Predis

Earlier, I used the KEYS command to find keys matching a specific pattern in my Redis database. Starting with Redis 2.8, the SCAN command seems preferable over KEYS because it returns an iterator instead of scanning the entire key space at once.

I am using Predis > = 0.8.5, which should support PHP iterators for the SCAN command. Predis doesn't have a lot of documentation, so I'm wondering how to translate the following KEYS command to its SCAN :

 $client->keys($pattern) 

I tried the following:

 $client->scan('MATCH', $pattern); 

What kind of work - but it does not return a native PHP iterator. It would be very useful to use the built-in support for the Predis iterator.

+7
php redis predis
source share
2 answers

I found how to do this in the Predis examples directory.

To use SCAN to find matching keys in a database, you simply use the Predis\Collection\Iterator\Keyspace :

 use Predis\Collection\Iterator; $client = ...; $pattern = 'foo*'; foreach (new Iterator\Keyspace($client, $pattern) as $key) { ... } 

Apparently, Predis has an iterator class in Predis\Collection\Iterator for each of the commands that return iterators:

  • Keyspace for SCAN
  • HashKey for HSCAN
  • SetKey for SSCAN
  • SortedSetKey for ZSCAN
  • ListKey for LRANGE - it doesn’t actually use Redis iterators, but it’s a good interface for LRANGE .
+15
source share

Perhaps this is useful for other Predis beginners, and you come from a PHP / MySQL background like me, you can use this:

 foreach (new Iterator\HashKey($client, $pattern) as $index => $value) { ... } 

When you previously generated an array dataset with $client->hmset($index, $array) .

0
source share

All Articles