我正在实施这个教程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/'} }}]}
很明显我在这里遗漏了一些东西,但我想不出来
您可以基于alternation构建动态正则表达式:
参见Python demo:
请注意,}将非常有用。你知道吗
Moss|Carrie\-Anne
将匹配Moss
或Carrie-Anne
。^如果在文本输入中有(
、+
和其他regex特殊字符,{相关问题 更多 >
编程相关推荐