Home > Enterprise >  Firestore query: how to filter by two fields
Firestore query: how to filter by two fields

Time:02-04

I want to filter documents by their location (using geohash) but I also want to order them by timestamp (to get the latest documents first). The following query fetches the nearby documents but they are not ordered by timestamp.

DocumentSnapshot<Object?>? lastFetchedDoc;  // used for pagination

Future<void> getReviews() async {

  Query<Map<String, dynamic>> query = firestore
            .collectionGroup("reviews")
            .where("city", whereIn: ['New York', 'Philadelphia', 'Washington'])
            .orderBy('geohash')
            .orderBy('timestamp', descending: true)
            .where('geohash', isGreaterThanOrEqualTo: "dph")
            .where('geohash', isLessThanOrEqualTo: "dp~")
            .limit(10);

  if (lastFetchedDoc != null) {
      query = query.startAfterDocument(lastFetchedDoc!);
  }

  QuerySnapshot snapshot = await query.get();
  lastFetchedDoc = snapshot.docs.last;
}
  

How can I create a query that fetches the nearby documents ordered by timestamp?

Thanks

CodePudding user response:

Your query results will first be ordered by geohash and only then on timestamp, meaning that the value of the timestamp field only affects the order of the results for documents where the value of geohash is the same.

There is no way to change this behavior for range queries such as the one you're doing. If you want to further process the documentation in order of timestamp, you will have to reorder them in your application code.

  • Related