1

If I have the following keys in my Redis:

Person:1234
Person:1234:email
Person:name:John
Person:lastName:Doe

I am trying to only MATCH the first key using SCAN.

I have tried with Person:*, but that of course returns all of them. Person:[^:]* or similar attempts did not work, I tried to match everything excluding the :.

Could someone point me in the right direction?

alturkovic
  • 990
  • 8
  • 31

1 Answers1

4

Redis scan match only support glob style matching. It cannot do regex matching. In order to achieve your goal, you have two options:

  1. Scan all keys and do matching on client side.
  2. Use Lua script to do the scan and matching. You can try the following one-liner as an example:
redis-cli eval 'local res = redis.call("scan", ARGV[1]); local matches = {}; for i,v in ipairs(res[2]) do if v == string.match(v, ARGV[2]) then matches[#matches+1] = v end end res[2] = matches; return res' 0 cursor-starting-from-0 'Person:[^:]*'

This one-liner returns results exactly like the built-in scan command. I'm not a Lua expert, and the code is not fully tested.

Also, Lua's matching is NOT regex matching, although it can solve most problems. You need to take Lua's reference to check if it matches your case.

for_stack
  • 21,012
  • 4
  • 35
  • 48