使用explain()查看mongodb查询语句的执行计划-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

        与mysql, oracle等关系数据库类似mongodb通过查询优化器为每一个查询语句计算出最优的查询计划 包括选择的索引 查询时间扫描的记录扫描的索引数量备选执行计划等信息。本文介绍使用explain()查看单个查询语句的执行计划。

explain()语法

        使用explain()获取查询语句的查询计划。语法如下

db.collections.explain().<method(…)>

        如查看db.orders.find()的执行计划

db.orders.explain().find()

{
	"explainVersion" : "2",
	"queryPlanner" : {
		"namespace" : "meituan.orders",
		"indexFilterSet" : false,
		"parsedQuery" : {
			
		},
		"queryHash" : "E475932B",
		"planCacheKey" : "66AC8600",
		"maxIndexedOrSolutionsReached" : false,
		"maxIndexedAndSolutionsReached" : false,
		"maxScansToExplodeReached" : false,
		"winningPlan" : {
			"queryPlan" : {
				"stage" : "COLLSCAN",
				"planNodeId" : 1,
				"filter" : {
					
				},
				"direction" : "forward"
			},
			"slotBasedPlan" : {
				"slots" : "$$RESULT=s4 env: { s1 = TimeZoneDatabase(Antarctica/Rothera...Antarctica/Vostok) (timeZoneDB), s3 = 1699514675958 (NOW), s2 = Nothing (SEARCH_META) }",
				"stages" : "[1] scan s4 s5 none none none none lowPriority [] @\"8e5238a3-24a2-4d90-ba2c-34c78b61f5ea\" true false "
			}
		},
		"rejectedPlans" : [ ]
	},
	"command" : {
		"find" : "orders",
		"filter" : {
			
		},
		"batchSize" : 1000,
		"projection" : {
			
		},
		"$readPreference" : {
			"mode" : "primary"
		},
		"$db" : "meituan"
	},
	"serverInfo" : {
		"host" : "XXXXXX-W11",
		"port" : 27017,
		"version" : "7.0.1",
		"gitVersion" : "425a0454d12f2664f9e31002bbe4a386a25345b5"
	},
	"serverParameters" : {
		"internalQueryFacetBufferSizeBytes" : 104857600,
		"internalQueryFacetMaxOutputDocSizeBytes" : 104857600,
		"internalLookupStageIntermediateDocumentMaxSizeBytes" : 104857600,
		"internalDocumentSourceGroupMaxMemoryBytes" : 104857600,
		"internalQueryMaxBlockingSortMemoryUsageBytes" : 104857600,
		"internalQueryProhibitBlockingMergeOnMongoS" : 0,
		"internalQueryMaxAddToSetBytes" : 104857600,
		"internalDocumentSourceSetWindowFieldsMaxMemoryBytes" : 104857600,
		"internalQueryFrameworkControl" : "trySbeEngine"
	},
	"ok" : 1
}

explain()的三种输出模式

        explain()默认按照queryPlanner 返回执行计划的内容。除了queryPlanner模式还有executionStats模式和allPlansExecution模式。三种模式使用方法如下。

  • 默认queryPlanner模式
db.collection.explain().find()
db.collection.explain(“queryPlanner”).find()
  • executionStats 模式
db.collection.explain(“executionStatus”).find()
  • allPlansExecution模式
db.collection.explain(“allPlansExecution”).find()

        三种模式返回的内容不同。 queryPlanner返回查询优化器中选择的执行计划如数据查询方式全表扫描COLLSCAN索引扫描IXSCAN等。在选择使用索引查询时返回查询时所需要的索引。”executionStats”模式下除了返回执行计划外还返回按照执行计划查询的执行信息包括执行时间扫描索引的数量扫描文档的数量每个查询阶段的执行信息。”allPlanExecution”模式除执行计划和执行信息外还包执行计划选择期间所有执行计划的统计信息包括备选方案的执行统计信息。通过查看执行计划可以查看数据库是否按照预期的方案执行给出数据库查询优化方案。如添加hint(), 删除或添加索引修改索引定义方式等来提高查询效率。

Explain()使用场景

        explain()适用于下面几种查询和数据更新语句。

  • aggregate()
  • find()
  • distinct()
  • count()
  • remove()
  • findAndModify()
  • group()
  • update()
  • mapReduce()

        对于数据更新的语句remove(), findAndModify(), update() 添加explain()后数据更新语句并不会真正的执行只是返回查询时使用的执行计划。

        Aggregation中包含$out, $merge语句时只能用默认模式即queryPlanner模式不可以使用executionStats模式和allPlansExecution模式。

        explain()使用时需要置于查询或更新的语句前面。

        db.collection.explain().find()和db.collection.find().explain()两个查询语句不同。db.collection.explain().find()在查询链中还可以添加更多的查询修饰语句。

        如 db.collection.explain().find().limit(1)

        Db.collection.explain().find().count().hint()等

        db.collection.find().explain()返回查询执行计划的cursor需要使用next()获取执行计划。后续不可以再添加查询修饰语句。

        使用db.collection.explain().help()获取explain的更多使用方法和帮助信息

db.order.explain().help()
Explainable operations
	.aggregate(...) - explain an aggregation operation
	.count(...) - explain a count operation
	.distinct(...) - explain a distinct operation
	.find(...) - get an explainable query
	.findAndModify(...) - explain a findAndModify operation
	.group(...) - explain a group operation
	.mapReduce(...) - explain a mapReduce operation
	.remove(...) - explain a remove operation
	.update(...) - explain an update operation
Explainable collection methods
	.getCollection()
	.getVerbosity()
	.setVerbosity(verbosity)

        使用db.collection.explain().find().help()获取查询修饰符和explain的cursor信息。

db.order.explain().find().help()
Explain query methods
	.finish() - sends explain command to the server and returns the result
	.forEach(func) - apply a function to the explain results
	.hasNext() - whether this explain query still has a result to retrieve
	.next() - alias for .finish()
Explain query modifiers
	.addOption(n)
	.batchSize(n)
	.comment(comment)
	.collation(collationSpec)
	.count()
	.hint(hintSpec)
	.limit(n)
	.maxTimeMS(n)
	.max(idxDoc)
	.min(idxDoc)
	.readPref(mode, tagSet)
	.showDiskLoc()
	.skip(n)
	.sort(sortSpec)

explain()实现机制

        实现上explain()封装了mongodb explain命令

  db.runCommand(
 {
     explain: <command>,
     verbosity: <string>,
     comment: <any>
   }
)

db.runCommand(
   {
     explain: { count: "products", query: { quantity: { $gt: 50 } } },
     verbosity: "queryPlanner"
   }
)

比较explain()与$indexStats

        两个命令都可以用于查看集合中定义的索引和执行信息。 但两个命令各有侧重点使用场景也不用。

        explain()返回查询语句的执行计划包含数据扫描方式 全表扫描COLLSCAN索引扫描IXSCAN等 还包括查询语句的执行时间扫描文档的数量扫描索引key的数量等。通过explain()技术人员可以发现查询是否需要添加索引或者对已有索引进行修改或增加hint()在引导查询优化器选用更好的执行计划。针对单个查询进行优化。

        $indexStatus 统计单个集合中所有索引定义和使用情况。包含索引定义的详细信息索引的命中信息等。针对使用较少的索引可以进行优化。

        实际运用中需要结合使用explain()和$indexStats两者的返回结果。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: go

“使用explain()查看mongodb查询语句的执行计划-CSDN博客” 的相关文章