本頁提供可用於查詢的索引策略範例 為多個欄位套用範圍與不等式篩選器 和查詢體驗的情況
最佳化查詢之前,請先參閱相關概念。
使用查詢說明功能最佳化查詢
如要判斷查詢與索引是否正確,您可以使用查詢 說明以取得查詢計畫摘要和執行統計資料 :
Java
Query q = db.collection("employees").whereGreaterThan("salary",
100000).whereGreaterThan("experience", 0);
ExplainResults<QuerySnapshot> explainResults = q.explain(ExplainOptions.builder().analyze(true).build()).get();
ExplainMetrics metrics = explainResults.getMetrics();
PlanSummary planSummary = metrics.getPlanSummary();
ExecutionStats executionStats = metrics.getExecutionStats();
System.out.println(planSummary.getIndexesUsed());
System.out.println(stats.getResultsReturned());
System.out.println(stats.getExecutionDuration());
System.out.println(stats.getReadOperations());
System.out.println(stats.getDebugStats());
Node.js
let q = db.collection("employees")
.where("salary", ">", 100000)
.where("experience", ">",0);
let options = { analyze : 'true' };
let explainResults = await q.explain(options);
let planSummary = explainResults.metrics.planSummary;
let stats = explainResults.metrics.executionStats;
console.log(planSummary);
console.log(stats);
以下範例說明如何運用正確的索引排序功能,減少 Cloud Firestore 掃描的索引項目數量。
簡易查詢
以收集員工的早期範例來說,
透過 (experience ASC, salary ASC)
索引執行如下:
Java
db.collection("employees")
.whereGreaterThan("salary", 100000)
.whereGreaterThan("experience", 0)
.orderBy("experience")
.orderBy("salary");
查詢掃描 95,000 個索引項目,只會傳回五份文件。由於查詢 不符合述詞的條件、讀取大量索引項目,但 過濾掉。
// Output query planning info { "indexesUsed": [ { "properties": "(experience ASC, salary ASC, __name__ ASC)", "query_scope": "Collection" } ], // Output Query Execution Stats "resultsReturned": "5", "executionDuration": "2.5s", "readOperations": "100", "debugStats": { "index_entries_scanned": "95000", "documents_scanned": "5", "billing_details": { "documents_billable": "5", "index_entries_billable": "95000", "small_ops": "0", "min_query_cost": "0" } } }
您可以從領域的專業能力中推測,大多數員工至少會
但少數薪資超過 100,000 人。鑑於此
深入分析,您會發現 salary
限制比
experience
限制。影響 Cloud Firestore 用於判斷的索引
執行查詢,指定可排序 salary
的 orderBy
子句
限制條件。experience
Java
db.collection("employees")
.whereGreaterThan("salary", 100000)
.whereGreaterThan("experience", 0)
.orderBy("salary")
.orderBy("experience");
當您明確使用 orderBy()
子句新增述詞時
Cloud Firestore 使用 (salary ASC, experience ASC)
索引執行查詢。
因為這項查詢中第一個範圍篩選器的選擇程度較高
與前一個查詢相比,查詢執行速度會較快且成本效益更高。
// Output query planning info { "indexesUsed": [ { "properties": "(salary ASC, experience ASC, __name__ ASC)", "query_scope": "Collection" } ], // Output Query Execution Stats "resultsReturned": "5", "executionDuration": "0.2s", "readOperations": "6", "debugStats": { "index_entries_scanned": "1000", "documents_scanned": "5", "billing_details": { "documents_billable": "5", "index_entries_billable": "1000", "small_ops": "0", "min_query_cost": "0" } } }