Cloud Firestore inequality operator exception flutter

Viewed 2595

while i have been using cloud firestore in my flutter app, strange exception occured.

EDITED

this is my code:

Stream<List<Product>> productsStream(int id) async* {
    final k = _db
        .collection('products')
        .where('category_id', isEqualTo: id)
        .where('stock', isGreaterThanOrEqualTo: 1)
        .orderBy('order')
        .snapshots();

    yield* k.map((event) => event.docs
        .map((e) => Product.fromJson(
              e.data(),
            ))
        .toList());

Here what i would like to achieve is to check for a product wether it is in stock and then to order products in an ascending order by order field in my products collection.

Here is my collection fields

But i am receiving this strange error:

Exception: 'package:cloud_firestore/src/query.dart': Failed assertion: line 421 pos 16: 'field == orders[0][0]': The initial orderBy() field '[[FieldPath([order]), false]][0][0]' has to be the same as the where() field parameter 'FieldPath([stock])' when an inequality operator is invoked.

What might be solution?

3 Answers

This is explained in the ordering limitations documentation:

If you include a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field

So I suspect you should have:

        .where('category_id', isEqualTo: id)
        .where('stock', isGreaterThanOrEqualTo: 1)
        .orderBy('stock')
        .orderBy('order')

Obviously that means it's no longer primarily ordered by order. You'd need to do local sorting if that's a problem - in which case you may find you don't want to order server-side at all.

Although "not equal to" filters aren't mentioned in the documentation, it sounds like they also count as range comparisons in terms of prohibiting filtering.

So basically, I would suggest you either need to filter locally on stock, or you need to order locally on order - you can't do both in the same Firestore query at the moment. Note that this server-side limitation is something that could change in the future (either for all range comparisons, or possibly just to allow "not equal to") so it may be worth retesting periodically.

You may need to do these two things. (it worked for me as shown in the example down below).

1 - Add an index for stock as Ascending in the console. This index should be in ascending.

2 - You must query based on that index.. So, as opposed to doing

...
.where('stock', isGreaterThanOrEqualTo: 1)
...

You should be doing

...
.orderBy('stock', descending: false)
.where('stock', isGreaterThanOrEqualTo: 1)
...

This applies to all other composite indexes that have equality checks. So you may need to do that for category_id

Also, here's my code for example

For context. I'm displaying a chat list, where the number of messages are greater than 0, and of-course, where the current user is a participant

1 - In GCP https://console.cloud.google.com/firestore/indexes/composite?project=**your-project-name** I added the required index as such Composite index setup

2 - Then finally, in my flutter code

static Future<QuerySnapshot> getUsersChatsList(String userId,
  {DocumentSnapshot? startAfterDoc, int limit = 10}) =>_chatsRef
    .where('participants_ids', arrayContains: userId)
    .orderBy('message_count', descending: false)
    .where('message_count', isNotEqualTo: 0)
    .orderBy('last_message_created_at', descending: true)
    .limit(limit)
    .get();

Ignore the limit & startAfterDoc as that was done for pagination

NOTICE that I had to manually order message_count in ASC before checking the condition.

And finally, of course, they're sorted in DESC in time.

You should make sure that you are ordering with the same constraint as your where like this:

   getInventory() async {
    String value = user.uid;
    return inventoryFirebaseReference
        .orderBy('availableStock')
        .where('userFirebaseId', isEqualTo: value)
        .orderBy('availableStock')
        .where('availableStock', isGreaterThan: 0)
        .snapshots()
        .listen((event) {
      chargeProducts = false;

      final _documentList = event.docs;

      //print(_documentList.length);

      _documentList.map((e) => {});

      List<ProductMoof> listProductsProv = _documentList.map((doc) {
        ProductMoof inventoryItemProv =
            ProductMoof.fromMap(doc.data() as Map<String, dynamic>);

        inventoryItemProv.firebaseId = doc.id;

        return inventoryItemProv;
      }).toList();

      listInventory = listProductsProv;

      notifyListeners();

      print('Update gotten from Menu');
    });
  }
Related