【问题标题】:How to create subcollection indexes at Cloud Firestore?如何在 Cloud Firestore 创建子集合索引?
【发布时间】:2017-10-31 06:35:04
【问题描述】:

我搜索并检查了 Cloud Firestore 文档,但没有发现有关如何声明子集合索引的信息。我已经声明了这样的内容

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

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

__escuser~1{uid}~1feeds__

不知道我是否正确创建了它。

【问题讨论】:

  • 抱歉,您能否澄清一下“子集合索引”的含义?你想做什么?
  • 有用户集合,每个user 集合都有另一个feeds 集合,我无法为子集合添加索引~firebase.google.com/docs/firestore/query-data/indexing
  • @Shaxrillo 我在某处看到有人提到此功能已计划但尚未实施。它不会在测试版中实施。我也想要这个功能

标签: firebase google-cloud-firestore


【解决方案1】:

当您创建索引时,它实际上会告诉您手动运行一次要创建索引的查询,然后它会生成一个 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();
    
  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" },
        ...
      ]
    }
  ]
}

或者直接进入数据库的管理面板并在那里添加供稿的索引。

【讨论】:

  • 谢谢@Chris 但我想手动添加它而不是通过自动生成的网址
  • 好吧,不管怎样,结果都是一样的,但是请看上面的内容。您没有指定“子集合路径”,而只是指定集合 ID @Shaxrillo
  • @Chris,但什么是“收藏 ID”?我的 Firestore 层次结构的不同部分中有多个同名的集合。例如/cars/{carIds}/models 和 /magazines/{magazineId}/models 如果我只是在“模型”上放置一个索引,firebase 会将索引应用于这两个集合吗?如果我希望能够相互独立地对它们进行索引,我是否必须为我的所有集合指定唯一的名称?
  • @Chris 我认为您误解了他想要的“子集合索引”的意义。它不索引到一个文档中的特定集合,而是索引每个文档中具有相同名称的每个集合。哪个在 Firestore 计划中但尚不存在
  • @Thaina 你确定这还不存在吗?你能指出你在哪里读到这篇文章吗?
【解决方案2】:

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

Cloud Firestore 索引基于集合名称,而不是完整的集合路径。所以如果你想在users/{id}/messages上创建索引,正确的做法是在messages上创建索引。

【讨论】:

    猜你喜欢
    • 2018-07-07
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2018-06-03
    • 1970-01-01
    • 2018-08-06
    相关资源
    最近更新 更多