Query Explain を使用してクエリ実行を分析する
このページでは、クエリを実行するときにクエリ実行情報を取得する方法について説明します。
クエリ Explain を使用する
Query Explain を使用すると、クエリの実行方法を把握できます。これにより、クエリの最適化に使用できる詳細情報が提供されます。
Query Explain は、 Google Cloud コンソールまたは explain
コマンドを使用して確認できます。
コンソール
クエリエディタでクエリを実行し、[説明] タブを開きます。
-
Google Cloud コンソールで、[データベース] ページに移動します。
- データベースのリストから、MongoDB 互換の Firestore データベースを選択します。 Google Cloud コンソールで、そのデータベースの Firestore エクスプローラが開きます。
- クエリエディタにクエリを入力し、[実行] をクリックします。
-
[説明] タブをクリックして、クエリ分析の出力を表示します。
MongoDB API
MongoDB API の Query Explain は、Mongo Shell や Compass などのツールで使用できる explain
コマンドでサポートされています。
explain
コマンドは、aggregate
、find
、distinct
、count
コマンドでサポートされています。次に例を示します。
db.collection.explain.find(...)
explain()
メソッドを使用することもできます。
db.collection.find({QUERY}).explain()
制限事項
次の制限事項と相違点に注意してください。-
Query Explain は、カーソルを返すコマンドをサポートしていません。たとえば、次のコマンドを直接呼び出して Explain を呼び出すことはサポートされていません。
db.collection.aggregate(..., explain: true)
Query Explain は、
find
、aggregate
、count
、distinct
コマンドでのみサポートされています。-
MongoDB API では、Query Explain の
Verbosity
オプションとComment
オプションはサポートされていません。この動作はexecutionStats
オプションと一致します。allPlansExecution
オプションとqueryPlanner
オプションは、指定されても無視されます。
分析
Query Explain の出力には、統計情報の概要と実行ツリーの 2 つの主要コンポーネントが含まれています。次のクエリを例に考えます。
db.order.aggregate(
[
{ "$match": { "user_id": 1234 } },
{ "$sort": { "date_placed": 1 } }
]
)
統計情報の概要
Query Explain の出力の上部には、実行統計の概要が表示されます。これらの統計情報を使用して、クエリのレイテンシやコストが高いかどうかを判断します。また、クエリがメモリ上限にどの程度近づいているかを示すメモリ統計情報も含まれています。
Billing Metrics:
read units: 1
Execution Metrics:
request peak memory usage: 4.00 KiB (4,096 B)
results returned: 1
実行ツリー
実行ツリーは、クエリの実行を一連のノードとして記述します。最下部のノード(リーフノード)は、ストレージ レイヤからデータを取得し、ツリーを上方向にトラバースしてクエリ レスポンスを生成します。
各実行ノードの詳細については、実行リファレンスをご覧ください。
この情報を使用してクエリを最適化する方法については、クエリの実行を最適化するをご覧ください。
実行ツリーの例を次に示します。
• Compute
| $out_1: map_set($record_1, "__id__", $__id___1, "__key__", $__key___1, "__row_id__", $__row_id___1, "__$0__", $__$0___2)
| is query result: true
|
| Execution:
| records returned: 1
|
└── • Compute
| $__$0___2: UNSET
|
| Execution:
| records returned: 1
|
└── • Compute
| $__key___1: UNSET
| $__row_id___1: UNSET
|
| Execution:
| records returned: 1
|
└── • Compute
| $__id___1: _id($record_1.__key__)
|
| Execution:
| records returned: 1
|
└── • MajorSort
| fields: [$v_5 ASC]
| output: [$record_1]
|
| Execution:
| records returned: 1
| peak memory usage: 4.00 KiB (4,096 B)
|
└── • Compute
| $v_5: array_get($v_4, 0L)
|
| Execution:
| records returned: 1
|
└── • Compute
| $v_4: sortPaths(array($record_1.date_placed), [date_placed ASC])
|
| Execution:
| records returned: 1
|
└── • Filter
| expression: $eq($user_id_1, 1,234)
|
| Execution:
| records returned: 1
|
└── • TableScan
source: **/my_collection
order: STABLE
properties: * - { __create_time__, __update_time__ }
output record: $record_1
output bindings: {$user_id_1=user_id}
variables: [$record_1, $user_id_1]
Execution:
records returned: 1
records scanned: 1
次のステップ
- 実行ツリーノードについては、クエリ実行リファレンスをご覧ください。
- クエリを最適化する方法については、クエリの実行を最適化するをご覧ください。