【问题标题】:Can I filter Multiple Fields in a Firestore search?我可以在 Firestore 搜索中过滤多个字段吗?
【发布时间】:2021-12-08 10:20:30
【问题描述】:

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

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

【问题讨论】:

    标签: firebase dart flutter google-cloud-firestore


    【解决方案1】:

    正如 creativecreator 或可能未解释的那样,没有直接的解决方案可以满足您的要求。根据数据库的大小,在客户端进行过滤可能会非常耗费时间和金钱。

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

    【讨论】:

    • 我正在使用 Firestore。在这种情况下,我们如何使用 where 条件 - 获取“(senderid == loggedinuserid and receiverid == 10)或(senderid == 10 and receiverid == loggedinuserid)”的所有聊天对话?请建议。谢谢。
    【解决方案2】:

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

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

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

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

    Flutter 中的解决方法概念

    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
    

    【讨论】:

    • 我正在使用 Firestore。在这种情况下,我们如何使用 where 条件 - 获取“(senderid == loggedinuserid and receiverid == 10)或(senderid == 10 and receiverid == loggedinuserid)”的所有聊天对话?请建议。谢谢。
    • @Kamlesh Firestore 不支持逻辑 OR 查询。您可以运行这两个查询并将它们合并到客户端,或者您可以例如创建一个包含两个用户的 participants 字段。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多