我可以在Firestore搜索中过滤多个字段吗?

问题描述 投票:0回答:2

我在我的应用程序中使用Firestore数据库。 现在,是否可以在多个字段中搜索特定单词?

例如:想象一个像“芝士蛋糕”这样的词。现在,我收集了100个文档,每个文档有10个不同的字段。 我可以在所有字段上过滤单词,以便在Flutter中的任何字段中返回包含单词“cheesecake”的任何文档吗?

firebase dart flutter google-cloud-firestore
2个回答
0
投票

不,你不能这样做。 看看Firebase Firestore Documentation page about queries,你会发现以下内容:

Cloud Firestore不支持以下类型的查询:

这并不直接适用于您的特定用例,但是您的请求无法工作的原因类似:没有索引允许您根据多个不同的字段进行排序。 你可以,例如创建对每个字段进行排序的索引,但只能单独查询它们。要了解为什么不支持某些查询,您可以使用check out this in depth explanatory video from the Firebase team

总而言之,这意味着您需要进行过滤客户端。

颤振中的变通方法概念

final QuerySnapshot querySnapshot = 
  await Firestore.instance.collection('cakes').getDocuments();
final List<DocumentSnapshot> documents = 
  querySnapshot.documents.where((snapshot) => snapshot.data.containsValue('cheesecake'));
// now the [documents] object will only contain documents, which have "cheesecake" as any of their fields

0
投票

正如creativecreatorormaybenot所解释的那样,没有直接的解决方案来满足您的要求。在客户端进行过滤可能非常耗费时间和金钱,具体取决于数据库的大小。

还有另一种可能性,即通过使用Algolia托管搜索服务在Cloud Firestore文档上启用全文搜索。有一个官方云函数示例,显示如何设置它:https://github.com/firebase/functions-samples/tree/Node-8/fulltext-search-firestore

© www.soinside.com 2019 - 2024. All rights reserved.