在python和mong中使用多个$regex子句创建$elemMatch查询

2024-09-25 10:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在实施这个教程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/'} }}]}

很明显我在这里遗漏了一些东西,但我想不出来


Tags: andofthetotextsearchqueryregex
1条回答
网友
1楼 · 发布于 2024-09-25 10:27:07

您可以基于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将匹配MossCarrie-Anne。^如果在文本输入中有(+和其他regex特殊字符,{}将非常有用。你知道吗

相关问题 更多 >