简体   繁体   English

Flutter FirebaseFirestore where 条件返回相关和不相关的值

[英]Flutter FirebaseFirestore where condition returning related and unrelated values

I am querying a firestore collection in Flutter using where and arrayContains, for some reason it is not working as expected for me.我正在使用 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'],
              ),
            );
          })

The _searchTerm variable is populated as I type in some values into the textfield and when it hits a length of three characters that's when the above query fires. _searchTerm 变量在我在文本字段中输入一些值时填充,当它达到三个字符的长度时,即触发上述查询。 For example when I type in test the query should only return the values that contain test in it, but I am getting the whole collection with and without the value test.例如,当我输入test时,查询应该只返回包含test的值,但我得到的是带有和不带有值 test 的整个集合。 Please advice!请指教!

EDIT - Posting a screenshot of my firestore data structure编辑 - 发布我的 Firestore 数据结构的屏幕截图在此处输入图像描述

When you do the following:当您执行以下操作时:

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

You are looking for documents inside the users collection that have _searchTerm as an item of the email array, property of a user document.您正在users集合中查找将_searchTerm作为email数组项的文档,该数组是user文档的属性。

There are two problems:有两个问题:

  1. I don't think the email property of your users is an array.我不认为您的usersemail属性是一个数组。
  2. Firebase does not perform substring searches Firebase 不执行 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 搜索

I think you will need to use a third-party application for searches on Firestore.我认为您将需要使用第三方应用程序在 Firestore 上进行搜索。 A popular one is Algolia that comes with a quite powerful FREE plan.一个流行的是Algolia ,它带有一个非常强大的免费计划。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM