How to use SCAN with the MATCH option in Predis

心已入冬 提交于 2020-01-22 05:53:05

问题


I have previously used the KEYS command to search for keys matching a certain pattern in my Redis database. Since Redis 2.8, the SCAN command seems to be preferred over KEYS since it returns an iterator instead of scanning through the whole keyspace at once.

I'm using Predis >= 0.8.5 which is supposed to 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 it's SCAN counterpart:

$client->keys($pattern)

I have tried the following:

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

Which kind of works - but it doesn't return a native PHP iterator. It would be really nice to use Predis' built-in iterator support.


回答1:


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

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

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 - This doesn't really use Redis iterators, but it's a nice interface to LRANGE anyway.



回答2:


Maybe this is helpful for other Predis beginners and you're coming 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).



来源:https://stackoverflow.com/questions/28545549/how-to-use-scan-with-the-match-option-in-predis

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