【发布时间】: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