首页 > 解决方案 > Firestore 搜索多个数组中的值

问题描述

我的每个 Firestore 文档中有两个数组。在我的应用程序中,您可以根据这些数组中的值进行搜索。如果我在基于选择的选项创建的数组之间查找完全匹配并在我的文档中查找完全匹配,我就能够使我的搜索工作。

let _ = circleQuery.observe(.documentEntered, with: { (key, location) in
            if let key = key {
                Constants.firestore.collection("facilities").whereField("facility_type", isEqualTo: self.type!)
                    .whereField("insurance_accepted", isEqualTo: self.insurance!).getDocuments { (querySnapshot, error) in
                        if let err = error {
                            print(err.localizedDescription)
                        } else {
                            for document in (querySnapshot?.documents)! {
                                if document.documentID == key {
                                    self.facilities?.append(document.data())
                                    self.addFaciltiesToMap()
                                }
                            }
                        }
                }
            }
        })

这样做的问题是,这不是在看个人价值观。我想根据两个文档数组中是否包含本地数组中的值来显示结果。用户可以从这些数组中的每一个中选择选项,并且他们不必从两者中进行选择,因此他们可以选择仅包含在其中一个或另一个中的选项。例如,他们可以从“facility_type”数组中选择 0 到 4 个选项,从“insurance_accepted”数组中选择 0 到 2 个选项。所以,如果他们只从“facility_type”中选择选项,我只想在该文档数组中查找选定的值,“insurance_accepted”文档数组也是如此。如果他们从两者中选择选项,我需要在两者中寻找选项。如果他们只从一个或另一个中选择,我需要根据他们选择的值是否存在于文档中的那个数组中来返回结果。如果他们同时选择两者,我需要根据每个文档数组中是否至少进行一个匹配来返回结果。

这基本上就是我想要实现的目标。

for value in self.type! {
                    Constants.firestore.collection("facilities").whereField("facility_type", arrayContains: value).getDocuments { (querySnapshot, error) in
                        if let err = error {
                            print(err.localizedDescription)
                        } else {
                            for document in (querySnapshot?.documents)! {
                                if document.documentID == key {
                                    self.facilities?.append(document.data())
                                }
                            }
                        }
                    }
                }

                for value in self.insurance! {
                    Constants.firestore.collection("facilities").whereField("insurance_accepted", arrayContains: value).getDocuments { (querySnapshot, error) in
                        if let err = error {
                            print(err.localizedDescription)
                        } else {
                            for document in (querySnapshot?.documents)! {
                                if document.documentID == key {
                                    self.facilities?.append(document.data())
                                }
                            }
                        }
                    }
                }

标签: iosarraysswiftgoogle-cloud-firestore

解决方案


推荐阅读