Lua script. Parameter order: matchKey, cursor

-- Print Start deleting logs
if (KEYS[2] = ="0") then redis.log(redis.LOG_NOTICE, "start scan del key:", KEYS[1]) end

-- Scan key. After testing, count at 10000 does not cause long blocking
local v = redis.call("SCAN", KEYS[2]."MATCH", KEYS[1]."COUNT".10000)

-- Traverses the key and deletes every 100 keys
local ks, size = {}, 0
for key, value in ipairs(v[2]) do
    ks[size + 1], size = value, size + 1
    if (size == 100) then
        redis.call("DEL".unpack(ks))
        ks, size = {}, 0
    end
end

-- Delete the remaining keys
if (size > 0) then
    redis.call("DEL".unpack(ks))
end

Delete logs after printing
if (v[1] = ="0") then redis.log(redis.LOG_NOTICE, "end scan del key:", KEYS[1]) end

Returns a cursor, and should end the loop if 0 is returned
return v[1]
Copy the code

It has the following characteristics

  • Simple input parameters are provided
  • Key traversal and deletion are performed by script, with no wasted traffic transferred to the client
  • Segmented scanning, scanning every 10000 keys, does not block REDis for a long time
  • Delete segments, call redis.del every 100 keys
  • Provides log printing at start and end

Directions for use

You should write a loop to invoke the script.

  1. The cursor should be 0 on the first call and return a cursor on success
  2. Pass the cursor obtained in the previous step as the new cursor value to the script. If cursor is 0, the traversal ends; otherwise, step 2 is repeated.

Sample code (pseudocode)

const LuaScanDelKeyScript = 'Script code' // This constant is written to the Lua script
const MatchKey = "*" // This is the matched key

var cursor int // The first call should set the cursor to 0
for {
    // Redis.Call means to Call the redis command. Please modify it to your own code according to different modules and languages.
    cursor = redis.Call("eval", LuaScanDelKeyScript, 2, MatchKey, cursor) // Simulate the eval command
    if cursor == 0 { // If the cursor is 0, the traversal is complete
        break}}Copy the code