在python和mongo中创建具有多个$regex子句$elemMatch查询



我正在实现本教程 如何将MongoDB正则表达式查询速度提高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/'} }}]}

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

您可以基于交替构建一个动态正则表达式:

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

请参阅Python演示:

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。 如果您的文字输入中有(+和其他正则表达式特殊字符,re.escape会很有帮助。

最新更新