0

I want to fetch the most liked posts of the last few days (3 days in this example).

Timestamp maxDaysAgoTimestamp =
        Timestamp.fromDate(DateTime.now().subtract(Duration(days: 3)));
Query query = FirebaseFirestore.instance
            .collection("posts")
            .where("timestamp",
                isGreaterThanOrEqualTo: maxDaysAgoTimestamp)
            .orderBy("likes", descending: true)
            .limit(10);
QuerySnapshot snapshot = await query.get();

I am trying to achieve this with the above query, but I am getting the following error.

Failed assertion: line 492 pos 13: 'conditionField == orders[0][0]':
The initial orderBy() field "[[FieldPath([likes]), true]][0][0]" has to be
the same as the where() field parameter "FieldPath([timestamp])" when an inequality
operator is invoked.

Appearently I would have to add an ordering on the timestamp as the first ordering, but then it would order by timestamp first and only consider the likes ordering when the timestamp is the same which is useless.

So am I doing something wrong? Or do you have any other ideas I could implement this use case?

In my opinion this use case is not too special, so there should be a way to do it.

tonik
  • 465
  • 1
  • 4
  • 15

1 Answers1

0

The error message is clear:

The problem is that you can't have it sorted by a field that's different than the field used in an inequality operator (isGreaterThanOrEqualTo in this case).

This basically means that since you're filtering using .where() on /timestamp, you need to orderBy in the same field as /timestamp.

The solution would therefore be to filter locally, after fetching the query. Something like:

docs.sort((a, b) => a.data()['likes'].compareTo(b.data()['likes']));
See also

How can I sort a list of strings in Dart?

MendelG
  • 14,885
  • 4
  • 25
  • 52
  • thank you, while this works it does not exactly achieve what I want, as you typically always fetch a batch with limit() and like this you only sort the post by likes of the batch, but you dont get the most liked posts of the last few days – tonik Jul 17 '23 at 14:32