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) 策略的更多信息,请查看官方文档。