简体   繁体   中英

get more than 10 documents from firestore in one round trip using Flutter

I am currently using whereIn for this. But only get 10 or less douments at once. whereIn 10 entries or less according to the firestore documentation

Is there any way to get more than 10 documents at once in one round trip?

 return _db
        .collection('books')
        .where('docId', whereIn: ['id1', 'id2'...'id10'])
        .get()
        .then((value) => value.docs.map((e) => BookModel.fromFireStore(e)).toList());

No, 10 is a hard limit and can't be exceeded. You will need to perform multiple queries to get more than 10 documents by ID. The documentation states:

Use the in operator to combine up to 10 equality (==) clauses on the same field with a logical OR.

The question has been answered. Here I just want to show how you can get those documents with multiple round-trips cause it is not an easy task as well. It took me some time to implement this, so I hope it will save someone else's time.

First create a function for one round-trip:

Future<List<Book>> _getBooksByIds(ids) {
  return _instance
      .collection('books')
      .where(FieldPath.documentId, whereIn: ids)
      .get()
      .then((QuerySnapshot snapshot) {
    return snapshot.docs.map((DocumentSnapshot doc) => BookModel.fromSnapshot(doc)).toList();
  });
}

Then split by 10 your ids

ids = ['id1', 'id2'...'id11'];
final idsBy10 = [
  for (var i = 0; i < ids.length; i += 10)
    ids.sublist(i, min(i + 10, ids.length))
];

Then run multiple requests and merge their results:

Future.wait<List<Book>>(idsBy10.map((ids) => _getBooksByIds(ids)))
        .then((listOfLists) => listOfLists.expand((l) => l).toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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