简体   繁体   English

如何使用 Cloud FireStore 查询两个日期范围之间的数据?

[英]How to query data between two dates range using Cloud FireStore?

I am trying to get a list of docs between two dates, but it is Invalid: Range filters on different fields我正在尝试获取两个日期之间的文档列表,但它无效:不同字段上的范围过滤器

Here is my code:这是我的代码:

await activationFBInstance
        .document('8thoOkTGYzVcntOxT2Av')
        .collection('posts')
        .where("startDate", isGreaterThan: Timestamp.fromDate(DateTime.now())).where("endDate", isLessThan: Timestamp.fromDate(DateTime.now()))
        .getDocuments()
        .then((value) {
      
      print(value.documents);
    }).catchError((onError) => print('error test 1 ' + onError.toString()));

The error message is pretty clear: you can only perform a range filter on a single field in Firestore.错误消息非常清楚:您只能对 Firestore 中的单个字段执行范围过滤。

The documentation on queries also has a good section on its limitations , which says:关于 查询的文档也有一个很好的部分关于它的限制,其中说:

In a compound query, range ( < , <= , > , >= ) and not equals ( != ) comparisons must all filter on the same field.在复合查询中,范围 ( <<=>>= ) 和不等于 ( != ) 比较必须都过滤同一字段。

So what you want isn't possible with Firestore at the moment.因此,目前 Firestore 无法实现您想要的。 You'll either have to filter on one field in the query and the other one in your application code, come up with a different data model that gets you a closer match to the use-case with Firestore's query capabilities, or consider using a database that better supports your needs.您必须过滤查询中的一个字段和应用程序代码中的另一个字段,提供不同的数据 model 以使您更接近具有 Firestore 查询功能的用例,或者考虑使用数据库更好地支持您的需求。

I also encountered the same problem when I was building an app.我在构建应用程序时也遇到了同样的问题。 I wanted to get users between the range of provided dates (inclusive).我想让用户在提供的日期范围(包括)之间。 For Example: Get users between 1 Jan 2020 to 1 May 2020 So what I did was the following.例如:在 2020 年 1 月 1 日到 2020 年 5 月 1 日之间获取用户所以我做了以下事情。

I calculated a Date Hash (Integer value) from the given date and stored it inside users database.我从给定的日期计算了一个日期 Hash(整数值)并将其存储在用户数据库中。 And when I was performing a query, I would get the hash value and compared it with the given range of dates.当我执行查询时,我会得到 hash 值并将其与给定的日期范围进行比较。

In Layman terms all I did was map a Date to a HashValue in ascending order and stored it and when getting the value from the range of dates I calculated the HashValue from both the dates and compared them.用外行的话来说,我所做的只是 map 一个日期到一个哈希值的升序并存储它,当从日期范围中获取值时,我从两个日期计算哈希值并比较它们。

Code For Hashing散列代码

int calculateDateHash(DateTime date) {
final int day = date.day;
final int month = date.month;
final int year = date.year;
final int initialYear = 2021;
final int lastCalculated = 403;
final int constantMultiplier = 31;

int value = month * constantMultiplier;

value = day + value;

value = value + (403 * (year - initialYear));

return value;
}

While storing a date in Firebase first calculate the Hash by supplying the date you want to store and store that hash value inside firestore.在 Firebase 中存储日期时,首先通过提供要存储的日期来计算 Hash,然后将 hash 值存储在 Firestore 中。

addUser(DateTime date) {
  FirebaseFirestore.instance
  .collection('yourCollection')
  .doc('yourDocument')
  .collection('yourCollection')
  .doc('yourDocument')
  .set({"dateHash": calculateDateHash(date)});
}

Code For Performing Query执行查询的代码

Future<QuerySnapshot> getUsersFromMaster(
DateTime fromDate,
DateTime toDate) async {
var ref = FirebaseFirestore.instance.collection(yourCollection).doc(yourDoc).collection(yourCollection);

if (toDate == fromDate) {
  return await ref
      .where('dateHash', isEqualTo: calculateDateHash(fromDate))
      .get();
}

return await ref
    .where('dateHash', isLessThanOrEqualTo: calculateDateHash(toDate))
    .where('dateHash', isGreaterThanOrEqualTo: calculateDateHash(fromDate))
    .get();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM