【发布时间】:2019-10-16 14:46:09
【问题描述】:
我正在使用 Firebase 中的一个集合来存储有关产品的信息。以前,我只是获取所有产品,然后在客户端对它们应用过滤器。有人告诉我,我需要通过查询应用这些过滤器,以减少 Firebase 需要的读取次数,因为会有大量产品。
我尝试将多个 .where() 语句链接在一起,但这并不能产生我需要的效果,我在另一篇文章中读到多个 .orderBy() 语句会破坏查询,但为了检查另一个输出的价格等字段告诉我我需要先 orderBy() 价格。可以应用任意数量的这些过滤器,或者它们都不能应用,具体取决于设置。我在一个单独的函数中使用底部的 lastVisible 变量作为 .startAfter 来获取更多产品。有什么方法可以产生我想以这种方式进行的那种查询吗?我还想知道是否可以执行类似 .where('field', isEqualTo: x or y or z) 的操作。
Query productQuery = Firestore.instance.collection('Products');
if(selectedCategories != null)
for(int i = 0; i < selectedCategories.length; i++)
productQuery = productQuery.where('category', isEqualTo: selectedCategories[i]);
if(minPrice > 0 && maxPrice > 0)
{
productQuery = productQuery.orderBy('price').where('price', isGreaterThanOrEqualTo: minPrice).where('price', isLessThanOrEqualTo: minPrice);
}
else if(minPrice > 0)
productQuery = productQuery.orderBy('price').where('price', isGreaterThanOrEqualTo: minPrice);
else if(maxPrice > 0)
productQuery = productQuery.orderBy('price').where('price', isLessThanOrEqualTo: maxPrice);
if(!showUnavailableItems)
productQuery = productQuery.where('status', isEqualTo: 'available');
switch(selectedCondition)
{
case 'Acceptable':
productQuery = productQuery
.where('condition', isEqualTo: 'Acceptable')
.where('condition', isEqualTo: 'Good')
.where('condition', isEqualTo: 'Very Good');
break;
case 'Good':
productQuery = productQuery
.where('condition', isEqualTo: 'Acceptable')
.where('condition', isEqualTo: 'Good');
break;
case 'Very Good':
productQuery = productQuery
.where('condition', isEqualTo: 'Acceptable');
break;
default:
break;
}
productQuery = productQuery.orderBy('id');
QuerySnapshot myQuery = await productQuery.getDocuments();
List<DocumentSnapshot> productSnaps = myQuery.documents;
print("INITIAL PRODUCT SNAPS LENGTH: ${myQuery.documents.length}");
if(productSnaps.length != 0)
lastVisible = productSnaps[productSnaps.length -1].data['id'];
应用条件或类别过滤器时,结果始终为 0 个文档。分别使用 minPrice 和 maxPrice 过滤器有效,但一起使用也会返回 0 个产品。除了在 Firebase 中创建索引的错误之外,我没有收到任何错误。
【问题讨论】:
标签: firebase flutter dart google-cloud-firestore