【问题标题】:Dialogflow to firestore inline editor javascript: sorting and filtering on different parameters of collectionDialogflow 到 Firestore 内联编辑器 javascript:对集合的不同参数进行排序和过滤
【发布时间】:2019-11-20 12:40:35
【问题描述】:

我在 Google Cloud Firestore 中有一个数据库,其中包含一组文档,每个文档都包含以下参数: 国家、标题、网址、日期。

我需要根据 Dialogflow 中的输入返回两个单独的内容。第一个是3条最新消息的头条,第二个是法国3条最新消息的头条。 我将在 Dialogflows 内联编辑器(即 javascript)中执行此操作,但它似乎与 javascript 并不完全相同,例如在节点中。

我已经用下面的代码解决了第一个问题:

function TopNews_Global(agent) {
      agent.add('Here are the latest Global news');

      let documents = db.orderBy('Date', 'desc').limit(3);      
    return documents.get()
      .then(snapshot => {
    snapshot.forEach(doc => {
          agent.add('-' + doc.data().Headline + '.');
          agent.add('Link:(' + doc.data().URL + ')');
        });
        return Promise.resolve('Read complete');
      }).catch(() => {
        agent.add('Error reading entry from the Firestore database.');
      });
  } 

db 是我在 firebase 中的收藏。 以下代码是我要返回的第二件事的解决方案,这就是我卡住的地方。无法像我一样对两个不同的字段进行过滤和排序。但是必须有办法解决这个问题 - 这是我想做的一件非常简单的事情。

https://firebase.google.com/docs/firestore/manage-data/export-import

function TopNews_France(agent) {
      agent.add('Here are the latest French news');

      let documents = db.orderBy('Date', 'desc').where('Country', '==', 'France').limit(3);       
    return documents.get()
      .then(snapshot => {
    snapshot.forEach(doc => {
          agent.add('-' + doc.data().Headline + '.');
          agent.add('Link:(' + doc.data().URL + ')');

        });
        return Promise.resolve('Read complete');
      }).catch(() => {
        agent.add('Error reading entry from the Firestore database.');
      });
  }

【问题讨论】:

    标签: javascript google-cloud-firestore dialogflow-es-fulfillment


    【解决方案1】:

    假设正如您所说,db 是一个集合对象,那么您的查询对于 Firestore 是有效的。

    db.orderBy('Date', 'desc').where('Country', '==', 'France').limit(3);
    

    Firestore 确实允许跨多个字段进行查询,假设只有 orderBy 或范围查询位于同一字段上。因此,您的查询 is valid(一个 orderBy 和一个在不同字段上的非范围 where)。

    你没有提到你遇到了什么错误,但我怀疑是这个(通常在 Javascript 控制台中可见):

    查询需要索引。你可以在这里创建它:(url)

    这是因为这是一个query which requires a composite index——它对一个字段进行排序并在另一个字段上进行过滤。

    因此,要解决此问题,您只需创建索引。在理想情况下,您只需单击该错误消息中的 URL 并被带到 Firebase 控制台中的确切位置以创建您需要的确切索引。如果由于某种原因您需要手动创建它,您也可以这样做through the console。完成构建后,您的查询应该可以工作了。

    在这种情况下,您将需要为 db 指向的任何集合创建一个索引,其中字段 Date(按降序排列)和 Country(按降序或升序排列——相等不会在意),并且具有收集范围。

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 2011-04-06
      • 2018-08-21
      相关资源
      最近更新 更多