本文内容为 http://www.redis.io/commands/keys 的翻译、注解、例子扩充及其它修改。感谢 Redis 作者 Antirez 为开源社区作出的贡献,本文保证最新、最准、最全以表示对其的敬意。欢迎留言纠错、提示更新或支持。
KEYS pattern

返回匹配模式的所有键。

Returns all keys matching pattern.

该操作的时间复杂度为 O(N),耗时已经极少。举个例子,当 Redis 运行在一台入门级笔记本上,它能够在 40 毫秒内扫描完带 100 万个键的数据库。

While the time complexity for this operation is O(N), the constant times are fairly low. For example, Redis running on an entry level laptop can scan a 1 million key database in 40 milliseconds.

注意 在产品实际使用环境下,使用命令 KEYS 必须非常小心。当它被执行于一个大数据库时,可能会拖垮性能。该命令被设计使用于调试或其它特殊操作,比如改变你的键命名空间层(Keyspace layout)。不要在你的常规代码中使用命令 KEYS。如果你在寻找一种方式来查找你的键命名空间中某个子集中的键,可以考虑使用集合数据结构(Set)

Warning: consider KEYS as a command that should only be used in production environments with extreme care. It may ruin performance when it is executed against large databases. This command is intended for debugging and special operations, such as changing your keyspace layout. Don't use KEYS in your regular application code. If you're looking for a way to find keys in a subset of your keyspace, consider using sets.

已支持的通配模式(Glob-style patterns)

  1. h?llo 匹配 hellohallohxllo
  2. h*llo 匹配 hlloheeeello
  3. h[ae]llo 匹配 hellohallo,但不匹配 hillo

使用 \ 来转义特殊字符,如果你希望按字面意义(Verbatim)匹配它们。

Supported glob-style patterns:

h?llo matches hello, hallo and hxllo

h*llo matches hllo and heeeello

h[ae]llo matches hello and hallo, but not hillo

Use \ to escape special characters if you want to match them verbatim.

  • 返回一列匹配模式的键。

    List of keys matching pattern.
  • redis> MSET one 1 two 2 three 3 four 4
    OK
    redis> KEYS *o*
    1) "four"
    2) "two"
    3) "one"
    redis> KEYS t??
    1) "two"
    redis> KEYS *
    1) "four"
    2) "two"
    3) "one"
    4) "three"
  • 版本支持

    1.0.0+

    时间复杂度(Time complexity)

    O(N),N 为数据库中键的个数。

    O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.