swift - Firebase 查询

标签 swift firebase filtering

假设我有这样的结构:

-users
  -user1_uid
    name
    distance
    age

我将如何进行查询(查找距离 <100 且年龄在 20 到 25 之间的用户)?

我试过标准方法

        let recentPostsQuery = (ref?.child("users").queryOrderedByChild("age").queryStartingAtValue("20"))!

M 问题是,这似乎无法查询多个 child (比如结合年龄和距离过滤)。与几个月前的 Firebase 相比,这方面有什么变化吗?我认为,在第一次查询后在本地过滤它们不是一种选择,因为可能有数千个对象。

最佳答案

我的第一选择是查询 20 到 25 之间的所有用户,然后在代码中过滤距离 < 100 的用户。

问题表明在代码中过滤不是一个选项,但我想在它有几千个节点或更少的情况下包括它以确保完整性:

    struct User { //starting with a structure to hold user data
        var firebaseKey : String?
        var theAge: Int?
        var theDistance: Int?
    }

    var userArray = [User]() //the array of user structures

    usersRef.queryOrderedByChild("age").queryStartingAtValue(20)
     .queryEndingAtValue(25).observeEventType(.Value, withBlock: { snapshot in

        for child in snapshot.children { //.Value so iterate over nodes

            let age = child.value["age"] as! Int
            let distance = child.value["distance"] as! Int
            let fbKey = child.key!

            let u = User(firebaseKey: fbKey, theAge: age, theDistance: distance)

            userArray.append(u) //add the user struct to the array
        }

        //the array to contain the filtered users
        var filteredArray: [User] = []
        filteredArray = userArray.filter({$0.theDistance < 100}) //Filter it, baby!

        //print out the resulting users as a test.
        for aUser in filteredArray {

            let k = aUser.firebaseKey
            let a = aUser.theAge
            let d = aUser.theDistance

            print("array: \(k!)  \(a!)  \(d!)")

        }

    })
}

现在是一个潜在的 super 简单的答案。

    let usersRef = self.myRootRef.childByAppendingPath("users")

    usersRef.queryOrderedByChild("age").queryStartingAtValue(20)
     .queryEndingAtValue(25).observeEventType(.ChildAdded, withBlock: { snapshot in

        let distance = snapshot.value["distance"] as! Int

        if distance < 100 {
            let age = snapshot.value["age"] as! Int
            let fbKey = snapshot.key!

            print("array: \(fbKey)  \(age)  \(distance)")
        }
    })

请注意,我们使用的是 .ChildAdded 而不是 .Value,因此每个节点一次读取一个 - 如果距离不是我们想要的,我们可以忽略它并继续下一个。

关于swift - Firebase 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37343375/

相关文章:

python - 在 Pandas 中过滤然后求和 Groupby 数据

ios - 'CGFloat' 不可转换为 'Float' 及更多

ios - 框架中的 Swift @IBInspectable 属性未显示给 Interface Builder

ios - 如何缓存 Firebase 数据以供离线使用?

android - 检索 firebase 字段的父项和子项

excel - 使用另一列值过滤一列

powershell - Where-Object 过滤器意外匹配整个输入集合,Get-Member 显示集合类型而不是元素类型

没有 cocoapods 的 iOS firebase Mach-O 链接器错误

ios - 如何访问通知(基础类)而不是我的(名为通知的自定义类)?

Swift 4 和 Firebase 附加所有带有用户名和个人资料图像错误的帖子