我是Firebase/swift新手,我試圖使用.indexOn對服務器上的一組節點進行排序。我搜索了SO和文檔以獲得編寫規則,但我正在努力使用索引的swift代碼的正確格式。Firebase&swift use.indexOn對數據快照進行排序
我的假設是,當我使用.indexOn規則時,返回的快照使用該索引來排序結果。通過在swift中使用.queryOrderedByChild(「title」),我否定了創建索引的服務器端性能優勢。如果這個假設不正確,請糾正我。
這裏是我的火力地堡DB結構的一個簡單的代碼片段:
{
"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代碼來使用索引(或更正索引,如果這是錯誤的)會很好。
我不完全清楚你的問題。添加索引後,您是否看到負面的性能影響?或者你的結果顯示不正常? –
嗨@FrankvanPuffelen - 請記住我是一個新手,所以我有點困惑。我的結果目前按照它們存儲在Firebase中的順序顯示,未按索引排序。我在文檔中讀到,最好在服務器上使用.indexOn進行排序,因此決定先做這件事(我的數據集可能會變得相當大),因此我無法在此階段評論性能。 – James
好吧,明白了。我會寫一個答案。對於未來的問題,最好只提一下出錯的部分。如果數組中的元素沒有按照您預期的順序排列,那麼使用索引時的性能影響是無關的 –