【问题标题】:Access last N documents of Google Firestore collection访问 Google Firestore 集合的最后 N 个文档
【发布时间】:2019-01-07 19:32:15
【问题描述】:

我想访问 google firestore 集合中的最后 N 个文档。文档的关键是 ISO 格式的时间戳。集合首先需要根据时间戳键进行排序,并且要检索最后更新的 N 个文档。此操作必须是实时且快速的。

events(collection) =>
documents as below:
2019-01-07T08:21:18.600Z => {
  symbolname: '10900CE',
  price: '10825.0',
  timestamp: '2019-01-07T13:51:18Z',
  quantity: '2.0',
  side: 'SELL' }
2019-01-07T08:21:28.614Z => { 
  symbolname: '10800PE',
  price: '10825.0',
  timestamp: '2019-01-07T13:51:28Z',
  quantity: '2.0',
  side: 'BUY' }
2019-01-07T09:45:24.783Z => { side: 'SELL',
  symbolname: '10800PE',
  price: '10805.0',
  timestamp: '2019-01-07T15:15:24Z',
  quantity: '2.0' }

我目前遍历集合并将键添加到数组中,然后对数组进行排序并通过这些键获取最后 N 个文档,如下所示:

var ids = []
db.collection('events').get()
  .then((snapshot) => {
    snapshot.forEach((doc) => {
      ids.push(doc.id)
    });
  })
  .then(()=>{
    //sortIds(ids);
    console.log(JSON.stringify(ids[ids.length-2])) //second last entry 2019-01-07T08:21:28.614Z
  })
  .catch((err) => {
    console.log('Error getting documents', err);
  });

如果集合大小增加,此操作需要很长时间。是否有实现此目的的最佳方法(排序/orderBy-descending 集合并获取最后 N 个文档)?

谢谢

【问题讨论】:

  • 您是否阅读过相关文档?有一整页描述了排序和限制。 firebase.google.com/docs/firestore/query-data/order-limit-data
  • 我经历了这个,但找不到 orderByKey 的方法。我可以使用诸如 dbRef.orderByKey().limitToLast(n); 之类的东西在 firebase 实时数据库中按键排序。有没有办法在不将键添加到对象中的情况下通过键对文档进行排序?
  • 您的文档中似乎已经有一个时间戳字段。你是说你不能用那个?
  • 是的,时间戳是出于其他目的的第三方时间戳。键中的时间戳是根据对象添加到数据库时的时间戳使其成为唯一条目。那么您是否建议我需要保留此时间戳以及对象的一部分?
  • 使用 FieldPath.documentId 作为排序键。 firebase.google.com/docs/reference/js/…

标签: javascript google-cloud-firestore


【解决方案1】:

大概是这样的:

db.collection('events').orderBy("timestamp").limit(n)

【讨论】:

  • 我曾经使用过这个,但是对于 100 个文档集合,返回 n 条目所花费的时间非常高~15 秒。我需要一种方法在不到 2 秒的时间内获取这些数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2019-08-16
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多