【问题标题】:Flutter FirebaseFirestore where condition returning related and unrelated valuesFlutter FirebaseFirestore where 条件返回相关和不相关的值
【发布时间】:2021-03-06 22:33:36
【问题描述】:

我正在使用 where 和 arrayContains 在 Flutter 中查询一个 firestore 集合,但由于某种原因它没有按预期工作。

      StreamBuilder(
          stream: (_searchTerm.length >= 3)
              ? FirebaseFirestore.instance.collection("users").snapshots()
              : FirebaseFirestore.instance
                  .collection('users')
                  .where('email', arrayContains: _searchTerm)
                  .snapshots(),
          builder: (ctx, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            final results = snapshot.data.docs;
            print(results.length);
            return ListView.builder(
              shrinkWrap: true,
              itemCount: results.length,
              itemBuilder: (ctx, index) => Text(
                results[index].data()['display-name'],
              ),
            );
          })

_searchTerm 变量在我在文本字段中输入一些值时填充,当它达到三个字符的长度时,即触发上述查询。 例如,当我输入 test 时,查询应该只返回其中包含 test 的值,但我得到的是带有和不带有值 test 的整个集合。 请指教!

编辑 - 发布我的 Firestore 数据结构的屏幕截图

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    当您执行以下操作时:

    FirebaseFirestore.instance
      .collection('users')
      .where('email', arrayContains: _searchTerm)
      .snapshots(),
    

    您正在寻找 users 集合内的文档,这些文档将 _searchTerm 作为 email 数组的一项,user 文档的属性。

    有两个问题:

    1. 我不认为您的 usersemail 属性是一个数组。
    2. Firebase 不执行子字符串搜索

    我认为您需要使用第三方应用程序在 Firestore 上进行搜索。一个受欢迎的是Algolia,它带有一个非常强大的免费计划。

    【讨论】:

    • 我已将数据结构添加到原始帖子中。使用该数据结构无法进行搜索吗?你能检查一下吗?谢谢
    • 是的,你看,emailString,而不是 array。当您对查询执行.where(property, arrayContains: value) 时,它将尝试查找具有名为property 的数组的所有文档,该数组包含value 作为数组的一项。它不适用于email,因为它是字符串而不是数组。它也不适用于searchTerm,因为它将是一个部分值。
    • 哦,是的,除了使用 3rd 方应用程序之外,我没有其他方法可以完成这项工作吗?
    • 恐怕不行。顺便说一下,Algolia 是 Google 推荐的解决方案:cloud.google.com/firestore/docs/solutions/search
    猜你喜欢
    • 2016-01-24
    • 2021-01-17
    • 2015-07-07
    • 2019-06-18
    • 1970-01-01
    • 2012-04-22
    • 2021-03-10
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多