[英]Google Firestore - How to get several documents by multiple ids in one round-trip?
[英]get more than 10 documents from firestore in one round trip using Flutter
我目前正在为此使用whereIn
。 但一次只能获得 10 个或更少的文件。 根据 firestore 文档,whereIn 10 个条目或更少
有没有办法在一次往返中一次获得超过 10 个文件?
return _db
.collection('books')
.where('docId', whereIn: ['id1', 'id2'...'id10'])
.get()
.then((value) => value.docs.map((e) => BookModel.fromFireStore(e)).toList());
不,10 是硬限制,不能超过。 您需要执行多个查询才能按 ID 获取 10 个以上的文档。 该文件指出:
使用
in
运算符将同一字段上的最多 10 个相等 (==) 子句与逻辑 OR 组合在一起。
问题已得到解答。 在这里,我只想展示如何通过多次往返获取这些文档,因为这也不是一件容易的事。 我花了一些时间来实现这个,所以我希望它能节省别人的时间。
首先为一次往返创建一个 function:
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();
});
}
然后除以 10 你的 id
ids = ['id1', 'id2'...'id11'];
final idsBy10 = [
for (var i = 0; i < ids.length; i += 10)
ids.sublist(i, min(i + 10, ids.length))
];
然后运行多个请求并合并它们的结果:
Future.wait<List<Book>>(idsBy10.map((ids) => _getBooksByIds(ids)))
.then((listOfLists) => listOfLists.expand((l) => l).toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.