我能在 Redis 值上执行正则表达式搜索吗?

huangapple 未分类评论88阅读模式
英文:

Can I perform a regex search on Redis values?

问题

我尝试使用RedisSearch,但那里只能执行模糊搜索,但我需要执行正则表达式搜索,例如:

  1. 键: "12345"
  2. 值: { 名称: "Maruti"}

搜索 "aru" 将返回结果 "Mumbai",基本上形成的正则表达式是 *aru*。有人能帮助我使用Redis实现吗?

英文:

I tried using RedisSearch but there you can perform a fuzzy search, but I need to perform a regex search like:

  1. key: "12345"
  2. value: { name: "Maruti"}

searching "aru" will give the result "Mumbai", basically the regex formed is *aru*. Can anyone help me out how can I achieve it using Redis ?

答案1

得分: 1

这是可行的,但我不建议这样做 - 性能会受到很大影响。

然而,如果必须这样做,您可以使用RedisGears来进行类似的即席正则表达式查询,如下所示:

  1. 127.0.0.1:6379> HSET mykey name Maruti
  2. (integer) 1
  3. 127.0.0.1:6379> HSET anotherkey name Moana
  4. (integer) 1
  5. 127.0.0.1:6379> RG.PYEXECUTE "import re\np = re.compile('.*aru.*')\nGearsBuilder().filter(lambda x: p.match(x['value']['name'])).map(lambda x: x['key']).run()"
  6. 1) 1) "mykey"
  7. 2) (empty array)

以下是为了可读性而提供的Python代码:

  1. import re
  2. p = re.compile('.*aru.*')
  3. GearsBuilder() \
  4. .filter(lambda x: p.match(x['value']['name'])) \
  5. .map(lambda x: x['key']) \
  6. .run()
英文:

This can be done, but I do not recommend it - performance will be greatly impacted.

If you must, however, you can use RedisGears for ad-hoc regex queries like so:

  1. 127.0.0.1:6379> HSET mykey name Maruti
  2. (integer) 1
  3. 127.0.0.1:6379> HSET anotherkey name Moana
  4. (integer) 1
  5. 127.0.0.1:6379> RG.PYEXECUTE "import re\np = re.compile('.*aru.*')\nGearsBuilder().filter(lambda x: p.match(x['value']['name'])).map(lambda x: x['key']).run()"
  6. 1) 1) "mykey"
  7. 2) (empty array)

Here's the Python code for readability:

  1. import re
  2. p = re.compile('.*aru.*')
  3. GearsBuilder() \
  4. .filter(lambda x: p.match(x['value']['name'])) \
  5. .map(lambda x: x['key']) \
  6. .run()

huangapple
  • 本文由 发表于 2020年8月15日 02:00:41
  • 转载请务必保留本文链接:https://java.coder-hub.com/63417879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定