在 swift 中查询 firebase 数据库的中间部分

query mid-section of firebase database in swift

我正在为一个大型数据库使用 firebase,每个条目都使用一个 autoid 键。例如,要获取最后十个条目,我可以使用:

ref.queryLimitedToLast(10).observeSingleEventOfType(.Value, withBlock: { snapshot in
            for item in snapshot.children {
                //do some code to each item
            }
        })

但是,我终其一生都想不出如何只获得之前的十个条目。例如。如果数据库有 100 个条目,我的代码将 return 90-100,但是我将如何获得条目 80-90(例如,不查询最后 20 个条目并丢弃一半,因为它看起来效率低下)?

编辑: 我最终使用了

ref.queryOrderedByChild("timecode").queryEndingAtValue(final).queryLimitedToLast(10).observeSingleEventOfType(.Value, withBlock: { snapshot in
for item in snapshot.children {
                //do some code to each item, including saving a new value of 'final'
            }
        })

并将值'final'保存为上次更新的时间码。也就是说,首先我会得到结果,比如 90-100,并将 90 的时间码保存为最终时间码(减去一秒),然后将其用作结束值,等等...以找到结果 80-89。 就像 Jay 在下面描述的那样,但是使用时间戳而不是索引号(因为它已经在那里)

编辑 2: 另外,为了让它更好地工作,我还在数据库的 firebase 规则中添加了 ".indexOn": "timecode"

您是否尝试过堆叠查询?

ref.queryLimitedToLast(20).queryLimitedToFirst(10).observeSingleEventOfType(.Value, withBlock: { snapshot in
    for item in snapshot.children {
        //do some code to each item
    }
})

一点想法,哈哈。

有几种方法可以做到这一点,但一个简单的解决方案是在另一个节点中保留一个 total_count,在每个节点中保留一个索引。

然后用queryStartingAtValue和queryEndingAtValue查询你感兴趣的子节点范围

例如,当您向 'posts' 节点添加一个子节点时,将一个子节点添加到 total_count 节点并保存。随着时间的推移,您将拥有 100 个帖子,并且 total_count 节点的值为 100。然后您可以查询任何范围的帖子:.queryStartingAtValue(80) 和 . queryEndingAtValue(89),或 .queryStartingAt(20) 和 .queryEndingAt(30)

例如,假设有 45 个帖子(此处仅显示其中 4 个)

posts
  ...
  post_1024
    text: "my post!"
    index: 42
  post_1025
    text: "another post"
    index: 43
  post_1026
    text: "yippee"
    index: 44
  post_1027
    text: "Stuff and Things"
    index: 45

然后一个节点来跟踪他们

post_info
   total_count: 45

以及查询中间两个节点的代码

let ref = myRootRef.childByAppendingPath("posts"
ref.queryOrderedByChild("index").queryStartingAtValue(43).queryEndingAtValue(44)
   .observeEventType(.Value, withBlock: { snapshot in
    print(snapshot.key)
})

输出为

  post_1025
    text: "another post"
    index: 43
  post_1026
    text: "yippee"
    index: 44

话虽这么说,这可能有点多余,具体取决于您的数据发生了什么。如果您从不删除帖子,那么您就设置好了。但是,如果您删除帖子,那么显然您的索引 (42, 43, .. 45) 存在差距,因此需要考虑其他因素。

您甚至可能不需要 total_count - 这仅取决于您的应用程序的工作方式。

您还可以利用节点上的优先级变量来存储索引,而不是将其作为子节点。

转换和带有 .Value 和 .numChildren 的 .observeSingleEvent 也可用于获取活动节点数。