我是一个firebase/swift新手,我正在尝试使用.indexon对服务器上的一组节点进行排序。我已经搜索了so和文档来编写规则,但是我正在努力寻找swift代码使用索引的正确格式。
我的假设是,当我使用.indexon规则时,返回的快照使用该索引对结果进行排序。通过在swift中使用.queryOrderedByChild(“title”),我否定了创建索引的服务器端性能优势。如果这个假设不正确,请纠正我。
下面是我的firebase数据库结构的一个简化片段:
{
"users": {
"GkdjgdBJh1TxuAzIPezLWRouG9f2": {
"messages": {
"-KM0crettRl-RLQQdmMQ": {
"body": "Anyone want a bit of body string?",
"title": "5 Another title string",
},
"-KM0dhkChY6ZQ2QzuPlC": {
"body": "This is a short body string",
"title": "1 A lovely title string",
},
"-FQ0dhkChY6ZQ2Qzu3RQv": {
"body": "Short and sweet body string",
"title": "3 I should be in the middle",
}
}
}
}
}
以下是我的规则json:
{
"rules": {
".read": true,
".write": true,
"users": {
"$userid": {
"messages": {
".indexOn": ["title"]
}
}
}
}
}
这是我的SWIFT代码:
if let user = FIRAuth.auth()?.currentUser {
// user is logged in
// *** I think this is the line with the issue ***
FIRDatabase.database().reference().child("users").child(user.uid).child("messages").observeEventType(.Value, withBlock: { (snapshot) in
messageArray = []
if let dictionaryOfMessages = snapshot.value as? [String: AnyObject] {
for messageKey in dictionaryOfMessages.keys {
messageArray.append(Message(json: JSON(dictionaryOfMessages[messageKey]!)))
// set the messageId
messageArray[messageArray.count - 1].messageId = messageKey
}
}
// return the data to the VC that called the function
success(messages: messageArray)
}) { (error) in
// Handle the Error
}
} else {
// return some generic messages about logging in etc.
}
任何关于如何修改swift代码以使用索引的建议都是非常好的。
最佳答案
当您请求数据时,需要使用queryOrderedByChild,并且在规则中有一个键。这里有一个例子;
Firebase文档
下面的示例演示如何检索按星号排序的用户最重要帖子的列表:
// My top posts by number of stars
let myTopPostsQuery = (ref.child("user-posts").child(getUid())).queryOrderedByChild("starCount")
此查询根据用户ID从数据库中的路径中检索用户的帖子,按每个帖子接收到的星星数排序。这种使用id作为索引键的技术称为数据扇出。
对queryOrderedByChild方法的调用指定了按顺序排列结果的子键。在这种情况下,文章按每个文章中“starcount”子项的值排序。有关如何排列其他数据类型的详细信息,请参见如何排列查询数据。
请按链接了解更多详细信息;
https://firebase.google.com/docs/database/ios/retrieve-data
关于swift - Firebase和Swift使用.indexOn对数据快照进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38266429/