Skip to content

Instantly share code, notes, and snippets.

@olzhas23
Forked from itamarhaber/Redis SCAN by "regex"
Created April 26, 2018 19:27
Show Gist options
  • Save olzhas23/4e1a07761d09a2d3c5fed9ad8457e7e1 to your computer and use it in GitHub Desktop.
Save olzhas23/4e1a07761d09a2d3c5fed9ad8457e7e1 to your computer and use it in GitHub Desktop.
Regex-like key name pattern matching in Redis
foo@bar:~$ redis-cli
127.0.0.1:6379> dbsize
(integer) 0
127.0.0.1:6379> set user:1 1
OK
127.0.0.1:6379> set use:the:force luke
OK
127.0.0.1:6379> set non:user a
OK
foo@bar:~$ redis-cli --eval scanregex.lua , "^user"
1) "user:1"
foo@bar:~$ redis-cli --eval scanregex.lua , "^user" 1
1) "use:the:force"
2) "non:user"
--[[
Use SCAN to search the entire keyspace and filter keys
with Lua patterns which are not POSIX regex, but ATM
(v3) the best thing available in Redis.
KEYS: none
ARGV: 1: Lua pattern (defaults to .* if unprovided)
2: Complement switch (i.e. not)
]]--
local re = ARGV[1]
local nt = ARGV[2]
local cur = 0
local rep = {}
local tmp
if not re then
re = ".*"
end
repeat
tmp = redis.call("SCAN", cur, "MATCH", "*")
cur = tonumber(tmp[1])
if tmp[2] then
for k, v in pairs(tmp[2]) do
local fi = v:find(re)
if (fi and not nt) or (not fi and nt) then
rep[#rep+1] = v
end
end
end
until cur == 0
return rep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment