某一天,監控到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很快就被佔滿了。ide
以後搜索了下,發現有多是正則表達式的問題。原來,雖然該語句的確是使用了索引,可是explain( )語句的輸出中還有一個字段"indexBounds",表示執行該語句時所需掃描的索引範圍。說實話,上面那個輸出中,我始終沒看明白它那個索引範圍。上面的語句對idField、dateField這兩個字段都進行了普通的正則表達式匹配,我猜想它應該是掃描了整個索引樹,因此致使索引並未實際提高該語句的查詢效率。spa
我看了下數據庫裏面的數據,發現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慢日誌中也未再出現該語句。開發