【问题标题】:Firebase Firestore combine ordered value with date range [duplicate]Firebase Firestore 将有序值与日期范围相结合 [重复]
【发布时间】:2021-03-03 15:54:55
【问题描述】:

假设我们有一个不断增长的餐厅数据库,用户可以喜欢它们。我想显示本月最受欢迎的 10 家餐厅。

我们确实需要一种降级的餐厅,并且我们需要定义一个范围。现在,当我偶然发现 firebase 文档时,我们在这里达到了极限。你将如何实现它?

QuerySnapshot snapshot = 
    await FirebaseFirestore.instance
    .collection('restaurants')
    .orderBy('likes', descending: true)
    .limit(10)
    .get()
    .catchError((error) => print("---- $error"));

在我的代码示例中,我们可以完成以下操作:

[x] get all restaurants ordered by likes descending
[x] limit them to the top 10
[ ] only pick restaurants of the last 30 days

假设每家餐厅都有一个uploadDate 值,即Timestamp。如何将我们的结果附上过去 30 天的uploadDate

【问题讨论】:

标签: firebase flutter google-cloud-firestore


【解决方案1】:

您可以在查询中添加 where() 子句 orderBy(...).where("uploadDate" > ....)

唯一的问题是,由于您使用了两个不同的字段(“likes”和“uploadDates”),因此您需要创建一个自定义索引。好消息是 Firestore 错误消息将为您提供要构建的确切索引

【讨论】:

    【解决方案2】:

    在您的情况下,为了能够将其与日期进行比较,您需要添加以下内容:

    final thirdyDaysAgo = DateTime.now().add(const Duration(days: -30));
    ...
    .where('uploadDate', isGreaterThanOrEqualTo: Timestamp.fromDate(thirdyDaysAgo))
    

    您首先需要确定 30 天前的日期(或您需要的任何日期),然后将其转换为 Timestamp 并在调用 .get() 之前在任何地方查询它。我没有尝试只放置一个 DateTime 对象,但如果不将日期转换为 Timestamp,它也可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2013-01-18
      • 2015-01-28
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      相关资源
      最近更新 更多