Redis SCAN matching

寵の児 提交于 2021-02-05 08:51:33

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/65288229/redis-scan-matching

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!