Home Database Redis Redis method of traversing all keys

Redis method of traversing all keys

Apr 21, 2020 am 09:06 AM
redis

Redis key command is used to manage redis keys. This article will introduce to you two methods in redis for traversing all keys in redis - KEYS pattern and SCAN cursor. I hope it will be of some help to you.

Redis method of traversing all keys

When we need to traverse all Redis keys or keys in a specified mode, the first thing that comes to mind is the KEYS command:

KEYS pattern
Copy after login

The official website has a tip for the KEYS command : KEYS is very fast. For example, it takes 40 milliseconds for Redis to execute a query in a database with 1 million keys. But using it in a large database may still cause performance problems. If you need to find specific KEYS from a data set, you'd better use Redis's collection structure SETS instead.

The KEYS command is very simple to use.

redis> MSET one 1 two 2 three 3 four 4
OK
redis> KEYS *o*
1) "four"
2) "one"
3) "two"
redis> KEYS t??
1) "two"
redis> KEYS *
1) "four"
2) "three"
3) "one"
4) "two"
redis>
Copy after login

But since the KEYS command returns all matching keys at once, when there are too many keys in redis, it is a hidden danger for memory consumption and the redis server.

For Redis 2.8 The above version provides us with a better command SCAN for traversing keys. The basic format of this command is:

SCAN cursor [MATCH pattern] [COUNT count]
Copy after login

SCAN. Each execution will only return a small number of elements, so it can be used in production environments without appearing. Issues like KEYS or SMEMBERS commands that may block the server.

The SCAN command is a cursor-based iterator. This means that every time the command is called, it needs to use the cursor returned by the previous call as the cursor parameter of the call, so as to continue the previous iteration process

When the cursor parameter of the SCAN command (i.e. cursor) When set to 0, the server will start a new iteration, and when the server returns a cursor with a value of 0 to the user, it means that the iteration has ended.

Simple iteration demonstration:

redis 127.0.0.1:6379> scan 0
1) "17"
2)  1) "key:12"
    2) "key:8"
    3) "key:4"
    4) "key:14"
    5) "key:16"
    6) "key:17"
    7) "key:15"
    8) "key:10"
    9) "key:3"
   10) "key:7"
   11) "key:1"
redis 127.0.0.1:6379> scan 17
1) "0"
2) 1) "key:5"
   2) "key:18"
   3) "key:0"
   4) "key:2"
   5) "key:19"
   6) "key:13"
   7) "key:6"
   8) "key:9"
   9) "key:11"
Copy after login

In the above example, the first iteration uses 0 as the cursor, indicating the start of a new iteration. The second iteration uses the cursor 17 returned in the first iteration as the new iteration parameter.

Obviously, the return value of the SCAN command is an array containing two elements. The first array element is the new cursor used for the next iteration, and the second array element is another array. This array contains all the elements being iterated.

Note: The returned cursor is not necessarily incrementing. The cursor returned may be smaller than the previous one.

When the SCAN command is called for the second time, the command returns cursor 0, which indicates that the iteration has ended and the entire data set has been completely traversed.

full iteration: Start a new iteration with 0 as the cursor, and keep calling the SCAN command until the command returns cursor 0. We call this process a complete traversal.

The SCAN incremental iteration command does not guarantee that each execution will return a given number of elements, and may even return zero elements, but as long as the cursor returned by the command is not 0, the application should not Treat the iteration as complete.

However, the number of elements returned by the command always complies with certain rules. For a large data set, the incremental iteration command may return up to dozens of elements each time; for a small enough data For a set, all keys may be returned in one iteration

COUNT option

For incremental iteration commands that do not guarantee the number of elements returned in each iteration, we can use the COUNT option, for The behavior of the command is adjusted to some extent. The purpose of the COUNT option is to let the user tell the iteration command how many elements should be returned from the data set in each iteration. Using the COUNT option is equivalent to a hint for incremental iteration commands. In most cases, this hint is more effective in controlling the number of return values.

Note: The COUNT option does not strictly control the number of keys returned, it can only be said to be a rough constraint. It is not necessary to use the same COUNT value in each iteration. The user can change the COUNT value in each iteration as needed. Just remember to use the cursor returned from the last iteration to the next iteration.

MATCH option

Similar to the KEYS command, the incremental iteration command is implemented by giving the MATCH parameter. By providing a glob-style mode parameter, the command only returns the given mode. matching elements.

MATCH option's pattern matching of elements is performed during the period after the command retrieves the elements from the data set and before returning the elements to the client, so if there are only a small number of elements and patterns in the iterated data set match, the iteration command may be executed multiple times without returning any elements.

The following is an example of this situation:

redis 127.0.0.1:6379> scan 0 MATCH *11*
1) "288"
2) 1) "key:911"
redis 127.0.0.1:6379> scan 288 MATCH *11*
1) "224"
2) (empty list or set)
redis 127.0.0.1:6379> scan 224 MATCH *11*
1) "80"
2) (empty list or set)
redis 127.0.0.1:6379> scan 80 MATCH *11*
1) "176"
2) (empty list or set)
redis 127.0.0.1:6379> scan 176 MATCH *11* COUNT 1000
1) "0"
2)  1) "key:611"
    2) "key:711"
    3) "key:118"
    4) "key:117"
    5) "key:311"
    6) "key:112"
    7) "key:111"
    8) "key:110"
    9) "key:113"
   10) "key:211"
   11) "key:411"
   12) "key:115"
   13) "key:116"
   14) "key:114"
   15) "key:119"
   16) "key:811"
   17) "key:511"
   18) "key:11"
redis 127.0.0.1:6379>
Copy after login

As can be seen, most of the above iterations do not return any elements. In the last iteration, we force the command to scan more elements for this iteration by setting the parameter of the COUNT option to 1000, so that the command returns more elements.

Based on the security of SCAN, it is recommended that everyone use the SCAN command instead of KEYS in the production environment. However, please note that this command was added after version 2.8.0. If your Redis is lower than this version , you need to upgrade Redis.

The following uses PHP code to demonstrate the use of the SCAN command:

<?php
 
$redis = new Redis();
 
$redis->connect(&#39;127.0.0.1&#39;, 6379);
 
 
/* 设置遍历的特性为不重复查找,该情况下扩展只会scan一次,所以可能会返回空集合 */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY);
 
$it = NULL;
$pattern = &#39;*&#39;;
$count = 50;  // 每次遍历50条,注意是遍历50条,遍历出来的50条key还要去匹配你的模式,所以并不等于就能够取出50条key
 
do
{
    $keysArr = $redis->scan($it, $pattern, $count);
 
    if ($keysArr)
    {
        foreach ($keysArr as $key)
        {
            echo $key . "\n";
        }
    }
 
} while ($it > 0);   //每次调用 Scan会自动改变 $it 值,当$it = 0时 这次遍历结束 退出循环
 
 
echo &#39;---------------------------------------------------------------------------------&#39; . "\n";
 
 
/* 设置扩展在一次scan没有查找出记录时 进行重复的scan 直到查询出结果或者遍历结束为止 */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
 
$it = NULL;
$pattern = &#39;*&#39;;
$count = 50;  // 每次遍历50条,注意是遍历50条,遍历出来的50条key还要去匹配你的模式,所以并不等于就能够取出50条key
 
//这种用法下我们只需要简单判断返回结果是否为空即可, 如果为空说明遍历结束
while ($keysArr = $redis->scan($it, $pattern, $count))
{
    foreach ($keysArr as $key)
    {
        echo $key . "\n";
    }
}
Copy after login

Execution results:

[root@localhost php]# /usr/local/php/bin/php scan.php 
bm
bm2
h1
name
bit
bm1
places
cities
hhl
---------------------------------------------------------------------------------
bm
bm2
h1
name
bit
bm1
places
cities
hhl
Copy after login

注意:如果php执行报错 请升级到较新版本的Redis扩展。

更多redis知识请关注redis入门教程栏目。

The above is the detailed content of Redis method of traversing all keys. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

What to do if redis-server can't be found What to do if redis-server can't be found Apr 10, 2025 pm 06:54 PM

Steps to solve the problem that redis-server cannot find: Check the installation to make sure Redis is installed correctly; set the environment variables REDIS_HOST and REDIS_PORT; start the Redis server redis-server; check whether the server is running redis-cli ping.

How to view all keys in redis How to view all keys in redis Apr 10, 2025 pm 07:15 PM

To view all keys in Redis, there are three ways: use the KEYS command to return all keys that match the specified pattern; use the SCAN command to iterate over the keys and return a set of keys; use the INFO command to get the total number of keys.

How to view the version number of redis How to view the version number of redis Apr 10, 2025 pm 05:57 PM

To view the Redis version number, you can use the following three methods: (1) enter the INFO command, (2) start the server with the --version option, and (3) view the configuration file.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to use redis zset How to use redis zset Apr 10, 2025 pm 07:27 PM

Redis Ordered Sets (ZSets) are used to store ordered elements and sort by associated scores. The steps to use ZSet include: 1. Create a ZSet; 2. Add a member; 3. Get a member score; 4. Get a ranking; 5. Get a member in the ranking range; 6. Delete a member; 7. Get the number of elements; 8. Get the number of members in the score range.

See all articles