【问题标题】:Creating $elemMatch query with multiple $regex clauses in python and mongo在 python 和 mongo 中使用多个 $regex 子句创建 $elemMatch 查询
【发布时间】:2019-03-12 20:31:54
【问题描述】:

我正在实施本教程How to Speed-Up MongoDB Regex Queries by a Factor of up-to 10 我正在使用最后指定的查询

db.movies.find({
$and:[{
    $text: {
        $search: "Moss Carrie-Anne"
    }},{
    cast: {
        $elemMatch: {$regex: /Moss/, $regex: /Carrie-Anne/}}
    }]}
);

我遇到的问题是如何生成子查询

$elemMatch: {$regex: /Moss/, $regex: /Carrie-Anne/}

使用 python 编程

到目前为止我的代码

def regexGen(s):
  d={}
  for word in s.split(" "):
    d["$regex"]= "/"+word+"/"  # this will of course save only the last value into the dict

  return (d)


query= {
    "$and":[{
        "$text": {
            "$search": "Moss Carrie-Anne"
        }},{
        "cast": {
            "$elemMatch": regexGen("Moss Carrie-Anne")}
        }
    ]
}

print (query)

#actual
# {'$and': [{'$text': {'$search': 'Moss Carrie-Anne'}}, {'cast': {'$elemMatch': {'$regex': '/Carrie-Anne/'}}}]}

#expected
# {'$and': [{'$text': {'$search': 'Moss Carrie-Anne'}}, {'cast': {'$elemMatch': {'$regex': '/Carrie-Anne/'}, {'$regex': '/Moss/'} }}]}

我显然在这里遗漏了一些东西,但无法弄清楚

【问题讨论】:

  • 试试def regexGen(s): return [("$regex", re.compile(re.escape(word))) for word in s.split()]
  • @WiktorStribiżew 这不会按预期产生输出。请注意,我需要将此发送回 pymongo 驱动程序。
  • 好吧,可能会接受一个正则表达式列表,试试d = {}、d["$regex"] = []、for word in s.split():、d["$regex"].append(re.compile(re.escape(word)))。见ideone.com/EEDYF9
  • @WiktorStribiżew 我试过你的方法,它引发了一个错误- pymongo.errors.OperationFailure: $elemMatch 需要一个对象
  • 好的,最简单的:创建一个基于替代的正则表达式来匹配任何单词:{ "$regex" : "|".join([re.escape(word) for word in s.split()]) }。仅查找整个单词,{ "$regex" : r"(?<!\w)(?:{})(?!\w)".format("|".join([re.escape(word) for word in s.split()])) }(或 r"(?<!\S)(?:{})(?!\S)" 仅在空格之间匹配)。

标签: python regex mongodb pymongo


【解决方案1】:

您可以基于alternation 构建动态正则表达式:

{ "$regex" : "|".join([re.escape(word) for word in s.split()]) }

见Python demo:

import re
s = "Moss Carrie-Anne"
print({ "$regex" : "|".join([re.escape(word) for word in s.split()]) })
# => {'$regex': 'Moss|Carrie\-Anne'}

请注意,Moss|Carrie\-Anne 将匹配 Moss 或 Carrie-Anne。如果您的文字输入中有 (、+ 和其他正则表达式特殊字符,re.escape 将很有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 2021-08-14
    • 2013-10-19
    • 2015-06-03
    • 2018-03-27
    相关资源
    最近更新 更多