swift - Swift firebase 查询有序搜索
问题描述
我想使用 queryStarting 在 firebase 中搜索
我有一个baseStruct:
products
Jakets
red
name: red
categoryName: Jakets
Pants
blue
name: blue
categoryName: Pants
...
我试过了
let strSearch = "re"
Database.database().reference().child("products").queryOrdered(byChild: "name")
.queryStarting(atValue: strSearch)
.queryEnding(atValue: strSearch + "\u{f8ff}")
.observeSingleEvent(of: .value, with: { (snapshot) in
print("snapshot= \(snapshot)")
})
在firebase中我添加了规则:
{
"rules": {
".read": true,
".write": true,
"products": {
"$someID": {
".indexOn": ["name"]
}
}
}
}
但它给了我
快照=快照(产品)空
如何更改我的代码以按名称搜索?
解决方案
Firebase 实时数据库查询功能适用于节点列表。您在某个位置执行查询,它会返回该位置的直接子节点,这些子节点在已知路径处具有特定值。
例如,您可以通过以下方式返回所有名称以开头的夹克re
:
Database.database().reference().child("products/Jakets").queryOrdered(byChild: "name")
.queryStarting(atValue: "re")
.queryEnding(atValue: "re\u{f8ff}")
.observeSingleEvent(of: .value, with: { (snapshot) in
...
})
但是您不能使用当前结构执行返回名称以 开头的夹克和裤子的查询re
。如果你想这样做,你将不得不:
- 对每种产品类型执行单独的查询。
- 或者添加一个额外的数据结构,将所有产品名称存储在一个平面列表中。
有关这方面的更多信息,请参阅: