Redis SCAN 匹配 [英] Redis SCAN matching

查看:35
本文介绍了Redis SCAN 匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的 Redis 中有以下键:

If I have the following keys in my Redis:

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

我正在尝试使用 SCANMATCH 第一个键.

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

我已经尝试过使用 Person:*,但这当然会返回所有这些.Person:[^:]* 或类似的尝试没有奏效,我尝试匹配除 : 之外的所有内容.

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?

推荐答案

Redis 扫描匹配仅支持 glob 样式匹配.它不能进行正则表达式匹配.为了实现您的目标,您有两种选择:

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

  1. 扫描所有密钥并在客户端进行匹配.
  2. 使用Lua脚本进行扫描和匹配.您可以尝试以下单行作为示例:

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:[^:]*'

这个单行返回的结果与内置的扫描命令完全一样.我不是 Lua 专家,代码没有经过全面测试.

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.

另外,Lua 的匹配不是正则匹配,虽然它可以解决大部分问题.您需要参考 Lua 的参考资料来检查它是否符合您的情况.

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.

这篇关于Redis SCAN 匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆