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

Sha*_*llo 13 firebase google-cloud-firestore

我用Google搜索并检查了Cloud Firestore文档,但没有发现如何声明子集合索引.我宣布过这样的话

...{    
  "collectionId": "user/{uid}/feeds",
  "fields": [..]
}...
Run Code Online (Sandbox Code Playgroud)

在索引选项卡中,它存储如下

__escuser~1{uid}~1feeds__
Run Code Online (Sandbox Code Playgroud)

我不知道我是否正确创造了它.

Chr*_*ris 12

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

在此输入图像描述

这是你如何做到的:

  1. 创建一个新目录
  2. npm init
  3. npm i --save firebase-admin
  4. 创建 index.js
  5. 将以下功能放在文档中

    const admin = require('firebase-admin');
    const serviceAccount = require('./firebase-creds.json');
    
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: 'https://projectId.firebaseio.com'
    });
    
    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();
    
    Run Code Online (Sandbox Code Playgroud)
  6. 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" },
        ...
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

或者只需进入数据库的管理面板,然后在那里添加feed的索引.

  • @Chris 我认为您误解了他想要的“子集合索引”的意义。它不是索引到一个文档中的特定集合,而是索引每个文档中具有相同名称的每个集合。哪个在firestore的计划中但还不存在 (2认同)

小智 6

这似乎由@ michael-bleigh在这里回答:https ://stackoverflow.com/a/47165007/2511985

Cloud Firestore索引基于集合名称,而不是完整的集合路径。因此,如果要在上创建索引users/{id}/messages,正确的方法是在上创建索引messages