本頁提供索引策略範例,適合以「範圍」和「使用不等式篩選器就能建立高效率的查詢體驗。
請先參閱相關概念,再最佳化 舉個簡單的例子,您可以定義情境 並指示 AI 如何回應服務中心查詢
使用查詢說明功能最佳化查詢
如要判斷使用的查詢和索引是否正確,您可以使用「查詢說明」功能,取得查詢計畫的摘要和執行統計資料:
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 個索引項目,只會傳回 5 份文件。不符合查詢述詞,因此會讀取大量索引項目,但會篩除。
// 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" } } }
我們可以從各領域的專業能力中推測出大多數員工至少都有一定經驗,但很少有薪資超過
100000。有鑑於此,我們可以得出結論,salary
限制比 experience
限制更嚴格。如要影響 Cloud Firestore 執行查詢時使用的索引,請指定 orderBy
子句,該子句可將 salary
限制排序在 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" } } }