我的 queryOrdered()
函数遇到问题,我不知道如何处理...
假设我的数据库结构是:
Planes{
Uid{
SE{
AutoID{
.Auto-Id
.Picture
.Registration
.Type
.model
}
AutoID{
//Same as first one
}
}
ME{
AutoID{
//Same as first one
}
}
}}
在我的数据库的这一部分中,我想通过 .Registration
运行搜索
所以我已将引用设置为 Planes > UId
执行此代码后:
var acftPickerSelected = aircrafts[listAcftsPicker.selectedRow(inComponent: 0)]
if let user = Auth.auth().currentUser{
// user is connect
let ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
let ev = ref.child("Planes").child(userID!)
ev.queryOrdered(byChild: "Registration").queryEqual(toValue: acftPickerSelected).observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in
for child in snapshot.children {
let value = snapshot.value as? NSDictionary
self.pickerRegi = value?["Registration"] as? String ?? "..unknown.."
self.stdbPickerType = value?["Type"] as? String ?? "..unknown.."
self.pickerModel = value?["model"] as? String ?? "..unknown.."
print("Avion : \(self.pickerRegi) - \(self.pickerModel) - \(self.stdbPickerType)")
}
}
但出现此消息:
2018-11-27 18:03:54.797824+0100 XXXXXXXXXX[12954:527986] 5.10.0 - [Firebase/Database][I-RDB034028] Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "Registration" at /Planes/BJMhmQzJXldULc5X9Y2WzjFEs9a2 to your security rules for better performance
所以我在 firebase 上添加了这样的规则:
{"rules": {
"Planes":{
"$uid":{
".indexOn": ["Registration"],
".write": "$uid === auth.uid",
".read": "$uid === auth.uid"
}
},
".read": true,
".write": true}}
现在错误消息不再出现,但是这部分没有任何反应:
self.pickerRegi = value?["Registration"] as? String ?? "..unknown.."
self.stdbPickerType = value?["Type"] as? String ?? "..unknown.."
self.pickerModel = value?["model"] as? String ?? "..unknown.."
print("Avion : \(self.pickerRegi) - \(self.pickerModel) - \(self.stdbPickerType)")
我该如何解决这个问题?
感谢您的帮助。
最佳答案
这里发生了两件事;
- 索引
- 观察者
在这种情况下,indexOn 不是问题。
indexOn 在生产应用程序中最重要,它基本上是查询性能的提高。为了进行测试,请首先消除该变量,因为它不是问题的原因。暂时将规则重置为默认
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
真正的问题是观察,因为它不够深入,无法获取您想要获取的数据。你错过了“SE”级别。这是重写的内容
let uidRef = ref.child("Planes").child(userID)
let seRef = uidRef.child("SE") //this is the child node to query
seRef.queryOrdered(byChild: "Registration").queryEqual(toValue: acftPickerSelected)
.observeSingleEvent(of: .value) { snapshot in
for child in snapshot.children {
let childSnap = child as! DataSnapshot
let dict = childSnap.value as! [String: Any]
let reg = dict["Registration"] as? String ?? "No Reg"
let mod = dict["model"] as? String ?? "No Model"
print(reg, mod)
}
}
按照您问题中的编写方式,查询将查询上一级:它期望在 SE 和 ME 节点正下方找到注册节点。但这些节点只包含 autoId 节点。
编辑:
通过扁平化(非规范化)来改变结构也是另一种选择
Planes
Uid
AutoID
.Auto-Id //note, if the is the same as the key, its not needed
.Picture
.Registration
.Type
.model
.se_or_me: "SE"
AutoID
.Auto-Id
.Picture
.Registration
.Type
.model
.se_or_me: "ME"
关于ios - 如何在 Firebase IOS 中搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53504884/