firebase 如何在Cloud Firestore创建子集合索引?

gijlo24d  于 2022-11-17  发布在  其他
关注(0)|答案(2)|浏览(128)

我在Google上搜索并检查了CloudFirestore文档,没有发现任何关于如何声明子集合索引的内容。

...{    
  "collectionId": "user/{uid}/feeds",
  "fields": [..]
}...

在索引选项卡中,它是这样存储的

__escuser~1{uid}~1feeds__

不知道我是否正确地创造了它或没有。

9w11ddsr

9w11ddsr1#

当你去创建一个索引时,它实际上告诉你运行一次你想手动创建索引的查询,然后它会生成一个URL,你可以复制粘贴到浏览器中,瞧!

这就是你的做法:
1.创建新目录

  1. npm init
  2. npm i --save firebase-admin
    1.创建index.js
    1.将以下函数放入文档中
const admin = require('firebase-admin');
 const serviceAccount = require('./firebase-creds.json');

 admin.initializeApp({
   credential: admin.credential.cert(serviceAccount),
   databaseURL: 'https://projectId.firebaseio.com'
 });

 const db = admin.firestore();

 function runQuery() {
   db
   .collection('users')
   .doc(someRandomUserId)
   .collection('feed')
   .where('read', '==', false)
   .where('timestamp', '<=', 1509889854742) //Or something else
   .get()
   .then(doc => {
     console.log(doc.data());
   })
   .catch(error => console.log(error));
 };
 runQuery();

1.运行node index.js
这会吐出这样的东西:
{ Error: The query requires an index. You can create it here: https://console.firebase.google.com/project/project-projectID/database/firestore/indexes?create_index=longRandomString ...}
复制链接并将其粘贴到浏览器中。

更新

要手动添加索引(通过CLI),可以执行以下操作:

{
  "indexes": [
    {
      "collectionId": "feed",
      "fields": [
        { "fieldPath": "read", "mode": "ASCENDING" },
        { "fieldPath": "timestamp", "mode": "ASCENDING" },
        ...
      ]
    }
  ]
}

或者直接进入数据库的管理面板,在那里添加提要索引。

p5fdfcr1

p5fdfcr12#

这似乎是由@michael-bleigh在这里回答:https://stackoverflow.com/a/47165007/2511985
Cloud Firestore索引基于集合名称,而不是完整的集合路径。因此,如果您想在users/{id}/messages上创建索引,正确的方法是在messages上创建索引。

相关问题