In Firebase, how can I query the most recent 10 child nodes?

前端 未结 3 909
醉话见心
醉话见心 2020-11-28 14:47

I\'m using childByAutoId() to generate my children. Each child looks like:

{
    user_id: 1
}

I\'d like to get the last 10 mos

3条回答
  •  甜味超标
    2020-11-28 15:21

    The answer is that you need to use a bit of reverse logic, and also store a timestamp key:value pair within each node as a negative value. I omitted the user_id: 1 to keep the answer cleaner.

    Here's the Firebase structure

    "test" : {
        "-KFUR91fso4dEKnm3RIF" : {
          "timestamp" : -1.46081635550362E12
        },
        "-KFUR9YH5QSCTRWEzZLr" : {
          "timestamp" : -1.460816357590991E12
        },
        "-KFURA4H60DbQ1MbrFC1" : {
          "timestamp" : -1.460816359767055E12
        },
        "-KFURAh15i-sWD47RFka" : {
          "timestamp" : -1.460816362311195E12
        },
        "-KFURBHuE7Z5ZvkY9mlS" : {
          "timestamp" : -1.460816364735218E12
        }
      }
    

    and here's how that's written out to Firebase; I just used a IBAction for a button to write out a few nodes:

    let testRef = self.myRootRef.childByAppendingPath("test")
    
    let keyRef = testRef.childByAutoId()
    
    let nodeRef = keyRef.childByAppendingPath("timestamp")
    
    let t1 = Timestamp
    
    nodeRef.setValue( 0 - t1) //note the negative value
    

    and the code to read it in

        let ref = self.myRootRef.childByAppendingPath("test")
        ref.queryOrderedByChild("timestamp").queryLimitedToFirst(3).observeEventType(.ChildAdded, withBlock: { snapshot in
            print("The key: \(snapshot.key)") //the key
        })
    

    and I declared a little function to return the current Timestamp

    var Timestamp: NSTimeInterval {
        return NSDate().timeIntervalSince1970 * 1000
    }
    

    and the output

    The key: -KFURBHuE7Z5ZvkY9mlS
    The key: -KFURAh15i-sWD47RFka
    The key: -KFURA4H60DbQ1MbrFC1
    

    As you can see, they are in reverse order.

    Things to note:

    1. Writing out your timestamp as negative values
    2. When reading in use .queryLimitedToFirst instead of last.

    On that note, you can also just read the data as usual and add it to an Array then then sort the array descending. That puts more effort on the client and if you have 10,000 nodes may not be a good solution.

提交回复
热议问题