how to get keys which does not match a particular pattern in redis? -
in redis, keys user*
print keys starting user
. example:
keys user* 1) "user2" 2) "user1"
now, want keys don't start user
printed. how that?
important: use scan
instead of (the evil) keys
redis' pattern matching functionally limited (see implementation of stringmatchlen
in util.c) , not provide seek atm. said, consider following possible routes:
- extend
stringmatchlen
match requirements, possibly submitting pr. - consider you're trying - fetching subset of keys going inefficient unless index them, consider tracking names of non-user keys (i.e.g. in redis set) instead.
- if insistent on scanning entire keyspace , match against negative patterns, 1 way accomplish little bit of lua magic.
consider following dataset , script:
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 ok
lua (save scanregex.lua
):
local re = argv[1] local nt = argv[2] local cur = 0 local rep = {} local tmp if not re re = ".*" end repeat tmp = redis.call("scan", cur, "match", "*") cur = tonumber(tmp[1]) if tmp[2] k, v in pairs(tmp[2]) local fi = v:find(re) if (fi , not nt) or (not fi , nt) rep[#rep+1] = v end end end until cur == 0 return rep
output - first time regular matching, 2nd time complement:
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"
Comments
Post a Comment