1
  "users":{
    "steve_rodriquez":{
        "ch1":{
             "timestamp":2
        },
        "ch2":{
            "timestamp":1
        },
        "ch3":{
            "timestamp":4
        },
        "ch4":{
            "timestamp":3
        }
    }   
}

Rules are defined as

 "rules": {
    ".read": true,
    ".write": true,
    "users":{
         ".indexOn": ["timestamp"] 
    }
  }

When i try to sort based on time stamp it doesnt work. i added 1,2,3,4 just for example

This is my client side code for it

ref = Database.database().reference()
        (ref.child("users").child("steve_rodriquez")).queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value, with: {(snapshot) in
            print(snapshot.value as Any)
        })
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
j.doe
  • 305
  • 3
  • 16

1 Answers1

2

When you retrieve the data from Firebase, the snapshot contains the keys, the values, and the order of all child nodes. But when you call snapshot.value it needs to convert this to a Dictionary, which only has space for the keys and the values. So at this point the information about the order of the child nodes is lost.

To maintain the order of the child nodes, iterate over the snapshot.children as shown in the documentation on listening for child events, and for example this answer: Iterate over snapshot children in Firebase

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks! that works. Just another question when i delete the index from the rules the query order still works. Do i really need to define the rules ? – j.doe Oct 09 '19 at 03:41
  • 1
    If you don't define an index, the ordering/filtering will be done client-side. So all data at the location will be downloaded to the client, and then ordered/filtered there. If you're only ordering this is just a bit slower. But if you're also filtering, you'll be wasting bandwidth this way. – Frank van Puffelen Oct 09 '19 at 14:14
  • thanks! So lets say i define the index in the rules and i order it by timestamp and also limit the result to 10 and implement pagination. Would it still be getting the entire result to the client side and order and then return the 10 results or would it only be bringing those 10 results to the client(saving bandwidth)? – j.doe Oct 09 '19 at 17:33
  • If you don't have an index, all data at the location will be downloaded to the client. – Frank van Puffelen Oct 09 '19 at 17:58