使用切碎欄位最佳化的查詢

本頁說明如何在 Firestore 中查看及控管切碎欄位的使用情形。這項功能適用於 Firestore Enterprise 版。

寫入文件時,Firestore 可能會判斷特定欄位應以切碎格式儲存。系統只會讀取必要欄位,而非完整文件,因此可提升查詢效能。

可從切碎欄位獲益的查詢

系統會對下列查詢形狀套用已切碎欄位的讀取作業 (如適用):

  • 匯總查詢:這類查詢只需要存取部分欄位,即可執行匯總作業。例如:

    db.pipeline()
      .collection("/customers")
      .where(lessThan("account_balance", 0))
      .aggregate(
        countAll().as("total"),
      )
    

    或使用 group-by:

    db.pipeline()
      .collection("/customers")
      .where(lessThan("account_balance", 0))
      .aggregate({
        accumulators: [
          field('account_balance').average().as('avg_account_balance')
        ],
        groups: [field('market_segment')]
      })
    
  • 投影查詢:只傳回特定欄位子集的查詢。例如:

    db.pipeline()
      .collection("/customers")
      .select("family_name", "given_name")
      .limit(10)
    
  • 篩選查詢:Firestore 查詢引擎判斷使用切碎欄位進行文件篩選有益的查詢。例如:

    db.pipeline()
      .collection("/customers")
      .where(equal("given_name", "alice"))
    

查看已清除欄位的使用情況

您可以使用查詢說明,檢查查詢是否使用切碎欄位。查詢計畫中的 TableScan 節點包含 Storage 區段,其中有下列指標:

  • 掃描形狀
    • shredded_fields_only:查詢只會讀取經過切碎的欄位。
    • shredded_fields_backjoin:查詢會從經過切碎的欄位讀取資料,並與原始文件聯結,以取得其他欄位。
  • 使用的欄位經過切碎:讀取為切碎欄位的欄位名稱清單。
  • 重新檢查計數:重新檢查計數器的地圖。重新檢查是指掃描撕碎的欄位時,會改為讀取原始完整文件。如果文件中的欄位值超過 8 KiB,就可能發生這種情況,因為這超過了切碎欄位儲存空間的大小上限。

輸出範例

...
└── • TableScan
        source: /customers
        order: UNDEFINED
        row range: (-∞..+∞)
        filter: ($account_balance_1 < 0L)
        output bindings: {$account_balance_1=account_balance, $market_segment_1=market_segment}
        variables: [$account_balance_1, $market_segment_1]

        Execution:
         records returned: 1,374
         latency: 26.58 ms
         post-filtered rows: 13,626
         records scanned: 15,000
         data bytes read: 23.73 MiB (24,887,141 B)

        Storage:
         scan shape: shredded_fields_only
         shredded fields used: [account_balance, market_segment]

控管已切碎欄位的使用情形

根據預設,Firestore 會在可用時使用切碎欄位。您可以使用 table_scan_method 查詢選項控制這項行為。

table_scan_method」選項支援的值:

  • shredded_fields_enabled (預設):使用已切碎的欄位 (如有)。
  • shredded_fields_disabled:請勿使用經過碎紙機處理的欄位。
  • force_shredded_fields:如果無法透過掃描已切碎的欄位完成資料表掃描,則查詢會失敗。

範例

var opts = new PipelineExecuteOptions()
    .with("table_scan_method", "shredded_fields_disabled");

var snapshot = db.pipeline()
    .collection("/customers")
    .where(equal("given_name", "alice"))
    .execute(opts)
    .get();

查詢效能警告

如果系統偵測到使用效率不彰的切碎欄位,Firestore 可能會在查詢說明結果中發出效能警告。例如:

  • 低選取性查詢:查詢掃描已切碎的欄位進行篩選,但篩除的文件太少,導致掃描效率不彰。

  • 高重新檢查查詢:查詢經常回溯至完整文件讀取,可能會影響效能。您可以使用 storage_size 等函式,找出觸發重新檢查的大型值。

在這種情況下,建議使用查詢選項停用已切碎的欄位讀取作業。

限制

Firestore 只會清除頂層欄位,此外,每個產品素材資源集合群組可清除的欄位數量也有限制。