在 Firebase 中,如何查询最近的 10 个子节点? [英] In Firebase, how can I query the most recent 10 child nodes?

查看:23
本文介绍了在 Firebase 中,如何查询最近的 10 个子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 childByAutoId() 来生成我的孩子.每个孩子看起来像:

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

{
    user_id: 1
}

我想获取最近添加的最后 10 个,按时间 DESC 排序.最简单的方法是什么?

I'd like to get the last 10 most recently added, sorted by time DESC. What's the easiest way to do this?

推荐答案

答案是你需要使用一点反向逻辑,并且还要在每个节点内存储一个时间戳 key:value 对作为负值.我省略了 user_id: 1 以保持答案更清晰.

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.

这是 Firebase 结构

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
    }
  }

这是写到 Firebase 的方式;我只是使用了一个 IBAction 作为一个按钮来写出几个节点:

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

以及读取它的代码

    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
}

和输出

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

如您所见,它们的顺序相反.

As you can see, they are in reverse order.

注意事项:

  1. 将时间戳记为负值
  2. 读取时使用 .queryLimitedToFirst 而不是 last.

在那一点上,您也可以像往常一样读取数据并将其添加到数组中,然后对数组进行降序排序.这会给客户端带来更多的工作量,如果您有 10,000 个节点,可能不是一个好的解决方案.

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.

这篇关于在 Firebase 中,如何查询最近的 10 个子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆