解决正则表示式匹配($regex)引起的一次mongo数据库cpu占用率高的问题
- 作者: 一不小心就帅了这么多年
- 来源: 51数据库
- 2021-08-18
某一天,监控到mongo数据库cpu使用率高了很多,查了一下,发现是下面这种语句引起的:
db.example_collection.find({
"idfield" :
{ "$regex" : "123456789012345678"
} ,
"datefield" :
{ "$regex" : "2019/10/10"
}})
通常,遇到这种情况,我第一反应是缺少相关字段的索引,导致每执行一次这种语句都会全表扫描一次。
但是我用explain( )语句分析了下,发现上面所涉及的两个字段idfield、datefield是有索引的,并且该语句也是有使用到索引的。如下为explain( )的结果:
mgset-11111111:primary> db.example_collection.find({ "idfield" : { "$regex" : "123456789012345678"} , "datefield" : { "$regex" : "2019/10/10"}}).explain("queryplanner")
{
"queryplanner" : {
"plannerversion" : 1,
"namespace" : "example_db.example_collection",
"indexfilterset" : false,
"parsedquery" : {
"$and" : [
{
"idfield" : {
"$regex" : "123456789012345678"
}
},
{
"datefield" : {
"$regex" : "2019/10/10"
}
}
]
},
"winningplan" : {
"stage" : "fetch",
"inputstage" : {
"stage" : "ixscan",
"filter" : {
"$and" : [
{
"idfield" : {
"$regex" : "123456789012345678"
}
},
{
"datefield" : {
"$regex" : "2019/10/10"
}
}
]
},
"keypattern" : {
"idfield" : 1,
"datefield" : 1
},
"indexname" : "idfield_1_datefield_1",
"ismultikey" : false,
"multikeypaths" : {
"idfield" : [ ],
"datefield" : [ ]
},
"isunique" : false,
"issparse" : false,
"ispartial" : false,
"indexversion" : 2,
"direction" : "forward",
"indexbounds" : {
"idfield" : [
"["", {})",
"[/123456789012345678/, /123456789012345678/]"
],
"datefield" : [
"["", {})",
"[/2019/10/10/, /2019/10/10/]"
]
}
}
},
"rejectedplans" : [ ]
},
"ok" : 1
}
查看mongo的日志发现,这种语句执行一次就要800~900ms,的确是比较慢。除非数据库cpu核数很多,要不然只要这种语句每秒并发稍微高一点,cpu很快就被占满了。
之后搜索了下,发现有可能是正则表达式的问题。原来,虽然该语句的确是使用了索引,但是explain( )语句的输出中还有一个字段"indexbounds",表示执行该语句时所需扫描的索引范围。说实话,上面那个输出中,我始终没看明白它那个索引范围。上面的语句对idfield、datefield这两个字段都进行了普通的正则表达式匹配,我猜测它应该是扫描了整个索引树,所以导致索引并未实际提升该语句的查询效率。
我看了下数据库里面的数据,发现idfield、datefield这两个字段完全没有必要进行正则匹配,进行普通的文本匹配就行。将正则匹配操作$regex去掉之后,再分析一下,结果是这样的:
mgset-11111111:primary> db.example_collection.find({ "idfield" : "123456789012345678", "datefield" : "2019/10/10"}).explain("queryplanner")
{
"queryplanner" : {
"plannerversion" : 1,
"namespace" : "example_db.example_collection",
"indexfilterset" : false,
"parsedquery" : {
"$and" : [
{
"idfield" : {
"$eq" : "123456789012345678"
}
},
{
"datefield" : {
"$eq" : "2019/10/10"
}
}
]
},
"winningplan" : {
"stage" : "fetch",
"inputstage" : {
"stage" : "ixscan",
"keypattern" : {
"idfield" : 1,
"datefield" : 1
},
"indexname" : "idfield_1_datefield_1",
"ismultikey" : false,
"multikeypaths" : {
"idfield" : [ ],
"datefield" : [ ]
},
"isunique" : false,
"issparse" : false,
"ispartial" : false,
"indexversion" : 2,
"direction" : "forward",
"indexbounds" : {
"idfield" : [
"["123456789012345678", "123456789012345678"]"
],
"datefield" : [
"["2019/10/10", "2019/10/10"]"
]
}
}
},
"rejectedplans" : [ ]
},
"ok" : 1
}
可以看到,仍然使用到了索引,并且索引扫描范围是仅限于一个值的。
后来跟开发人员确认了下,该语句确实没必要使用正则匹配,就让他把正则匹配去掉了。之后就没有再出现问题了,mongo慢日志中也未再出现该语句。
总结
以上所述是小编给大家介绍的解决正则表示式匹配($regex)引起的一次mongo数据库cpu占用率高的问题,希望对大家有所帮助
