我在 Firestore 开发数据库上设置了多个不同的索引。现在,我想将它们导出到
firestore.indexes.json
中,以便设置 prod 环境的过程会更容易。有没有办法使用 Firebase CLI 导出这些索引?这同样适用于安全规则,尽管我知道我可以复制粘贴它们。
有可能!
从 Firebase 项目文件夹中的 CLI
firebase firestore:indexes
运行。
如果您已经设置了索引并通过 CLI 登录到 Firebase,您将获得格式化的 JSON 输出供您复制。
示例:
{
"indexes": [
{
"collectionId": "teslaData",
"fields": [
{
"fieldPath": "Model",
"mode": "ASCENDING"
},
{
"fieldPath": "Price",
"mode": "ASCENDING"
}
]
}
]
}
可以使用
firebase deploy --only firestore:indexes
重新导入导出的索引。检查以下文档摘录。
https://firebase.google.com/docs/firestore/query-data/indexing
您还可以使用 Firebase CLI 部署索引。首先,运行 firebase init firestore 在您的项目目录中。在设置过程中, Firebase CLI 生成一个 JSON 文件,其中包含默认索引 正确的格式。编辑文件以添加更多索引并使用 firebase 部署命令。如果只想部署索引,则添加 --only firestore:indexes 标志。如果您对索引进行编辑 使用 Firebase 控制台,请确保您还更新了本地 索引文件。
我正在使用 Firebase CLI
4.2.1
(如果有帮助的话)。
编辑:截至
9.6.0
,它仍然有效。
在您的 Firebase 项目文件夹中,在终端中执行以下命令:
firebase firestore:indexes > firestore.indexes.json
它将保存一个名为 firestore.indexes.json 的文件以及您的索引。
然后您可以将该文件上传到其他 Firebase 项目。
这就是我的项目文件的布局方式
myProjectFolder
.firebaserc
firebase.json
firestore.indexes.json
functions
运行命令
firebase use myApp-dev
然后运行 firebase firestore:indexes > firestore.indexes.json
将当前开发项目的索引导出到文件
myApp-dev
和 myApp-prod
是“项目 ID”。要在 Firebase 中找到它,请单击“项目概述”旁边的齿轮 --> 项目设置 --> 常规选项卡(您应该在下面看到它)在文件
firebase.json
中,确保它指向导出的 firestore.indexes.json
的索引:
{
"functions": [
{
"source": "functions",
"codebase": "default",
"ignore": [
"node_modules",
".git",
"firebase-debug.log",
"firebase-debug.*.log"
],
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint",
"npm --prefix \"$RESOURCE_DIR\" run build"
]
}
],
"firestore": {
"indexes": "firestore.indexes.json"
}
}
firebase use myApp-prod
和 firebase deploy --only firestore:indexes
如果接受的答案对 Firestore 索引不起作用(我收到权限错误),您可以转到 Firebase 控制台 > Cloud Firestore > 索引,然后在检查器中打开网络选项卡,清除所有请求并刷新页面。页面加载后,您可以在网络请求的 XHR 过滤器中找到索引的 JSON 格式响应(我通过在网络选项卡的搜索栏中搜索“索引”一词找到了我的)。它应该看起来像“indexes?key=...”,您可以复制此 JSON 响应。
如果您已经使用
firebase init
在项目中初始化了 firebase,则只需将其粘贴到项目的 firestore.indexes.json 文件中即可。
然后将每个 name 属性更改为 collectionGroup 属性。例如:'name': 'projects/[your project name]...'
至 'collectionGroup': '[name of collection for this index]'
运行
firebase deploy --only firestore:indexes
将文本编辑器中所做的任何更改更新回 Firestore 索引选项卡
对于 Firestore 安全规则,以不太复杂但类似的方式,您可以将 Firebase 控制台中显示的规则复制并粘贴到项目的 firestore.rules 文件中。
样本
firestore.indexes.json
文件
{
"indexes": [
{
"collectionGroup": "faq",
"queryScope": "COLLECTION",
"fields": [
{
"fieldPath": "searchKeywords",
"arrayConfig": "CONTAINS"
},
{
"fieldPath": "answered",
"order": "ASCENDING"
},
{
"fieldPath": "relevanceScore",
"order": "ASCENDING"
},
{
"fieldPath": "__name__",
"order": "ASCENDING"
}
]
}
]
}
要使用 gcloud 控制台以 json 格式导出索引,请使用
gcloud firestore indexes composite list --format json
Cloud Firestore 索引定义参考页面显示了具体操作方法。
您可以使用 firebase 通过 CLI 导出索引
。
firestore:indexes