Cloud Firestore 會自動建立索引以支援最常見的查詢類型,但允許您定義自訂索引和索引覆蓋,如Cloud Firestore 指南中所述。
您可以在 Firebase 控制台中或使用 CLI 建立、修改和部署自訂索引。從 CLI 中,使用預設檔名firestore.indexes.json
編輯索引設定文件,並使用firebase deploy
指令進行部署。
您可以使用firebase firestore:indexes
透過 CLI 匯出索引。
索引設定檔定義一個包含indexes
陣列和可選fieldOverrides
陣列的物件。這是一個例子:
{
// Required, specify compound indexes
indexes: [
{
collectionGroup: "posts",
queryScope: "COLLECTION",
fields: [
{ fieldPath: "author", arrayConfig: "CONTAINS" },
{ fieldPath: "timestamp", order: "DESCENDING" }
]
}
],
// Optional, disable indexes or enable single-field collection group indexes
fieldOverrides: [
{
collectionGroup: "posts",
fieldPath: "myBigMapField",
// We want to disable indexing on our big map field, and so empty the indexes array
indexes: []
}
]
}
部署索引配置
使用firebase deploy
指令部署索引配置。如果您只想為專案中配置的資料庫部署索引,請新增--only firestore
標誌。請參閱此指令的選項參考。
若要列出已部署的索引,請執行firebase firestore:indexes
指令。新增--database=<databaseID>
標誌以列出項目預設資料庫以外的資料庫的索引。
如果您使用 Firebase 控制台對索引進行編輯,請確保也更新本機索引檔案。有關管理索引的更多信息,請參閱Cloud Firestore 指南。
JSON格式
索引
indexes
數組中一個物件的架構如下。可選屬性用?
來識別。特點。
請注意,Cloud Firestore 文件欄位只能在一個模式下建立索引,因此欄位物件不能同時包含order
和arrayConfig
屬性。
collectionGroup: string // Labeled "Collection ID" in the Firebase console
queryScope: string // One of "COLLECTION", "COLLECTION_GROUP"
fields: array
fieldPath: string
order?: string // One of "ASCENDING", "DESCENDING"; excludes arrayConfig property
arrayConfig?: string // If this parameter used, must be "CONTAINS"; excludes order property
字段覆蓋
fieldOverrides
數組中一個物件的架構如下。可選屬性用?
來識別。特點。
請注意,Cloud Firestore 文件欄位只能在一個模式下建立索引,因此欄位物件不能同時包含order
和arrayConfig
屬性。
collectionGroup: string // Labeled "Collection ID" in the Firebase console
fieldPath: string
ttl?: boolean // Set specified field to have TTL policy and be eligible for deletion
indexes: array // Use an empty array to disable indexes on this collectionGroup + fieldPath
queryScope: string // One of "COLLECTION", "COLLECTION_GROUP"
order?: string // One of "ASCENDING", "DESCENDING"; excludes arrayConfig property
arrayConfig?: string // If this parameter used, must be "CONTAINS"; excludes order property
TTL政策
可以使用fieldOverrides
數組啟用或停用 TTL 策略,如下所示:
// Optional, disable index single-field collection group indexes
fieldOverrides: [
{
collectionGroup: "posts",
fieldPath: "ttlField",
ttl: "true", // Explicitly enable TTL on this Field.
// Disable indexing so empty the indexes array
indexes: []
}
]
要保留欄位中的預設索引並啟用 TTL 策略:
{
"fieldOverrides": [
{
"collectionGroup": "yourCollectionGroup",
"fieldPath": "yourFieldPath",
"ttl": true,
"indexes": [
{ "order": "ASCENDING", "queryScope": "COLLECTION_GROUP" },
{ "order": "DESCENDING", "queryScope": "COLLECTION_GROUP" },
{ "arrayConfig": "CONTAINS", "queryScope": "COLLECTION_GROUP" }
]
}
]
}
有關生存時間 (TTL) 策略的更多信息,請查看官方文件。