如何在 Predis 中使用 SCAN 和 MATCH 选项

How to use SCAN with the MATCH option in Predis

我以前使用过 KEYS command to search for keys matching a certain pattern in my Redis database. Since Redis 2.8, the SCAN 命令似乎优于 KEYS,因为它 return 是一个迭代器而不是一次扫描整个键空间。

我正在使用 Predis >= 0.8.5,它应该支持 SCAN 命令的 PHP 迭代器。 Predis 没有很多文档,所以我想知道如何将以下 KEYS 命令翻译成它的 SCAN 对应命令:

$client->keys($pattern)

我尝试了以下方法:

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

哪种类型的作品 - 但它不是 return 本机 PHP 迭代器。如果使用 Predis 的内置迭代器支持,那就太好了。

我在 Predis examples directory 中找到了如何操作。

要使用 SCAN 在数据库中搜索匹配的键,您只需使用 Predis\Collection\Iterator\Keyspace class:

use Predis\Collection\Iterator;

$client = ...;
$pattern = 'foo*';

foreach (new Iterator\Keyspace($client, $pattern) as $key) {
    ...
}

显然 Predis 在 Predis\Collection\Iterator 中有一个迭代器 class 用于 return 个迭代器的每个命令:

  • Keyspace 对于 SCAN
  • HashKey 对于 HSCAN
  • SetKey 对于 SSCAN
  • SortedSetKey 对于 ZSCAN
  • ListKey for LRANGE - 这并没有真正使用 Redis 迭代器,但它是 LRANGE 的一个很好的接口。

也许这对其他 Predis 初学者有帮助,如果你像我一样来自 PHP/MySQL 背景,你可以使用这个:

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

当您之前使用 $client->hmset($index, $array).

生成数组数据集时