【问题标题】:Firebase request range of rowsFirebase 请求的行范围
【发布时间】:2017-07-27 11:23:21
【问题描述】:

我每分钟都在存储用户的lat, lng, timestamp。 我只想读取基于timestamp 的部分数据。我试过下面的查询,没有用。还要检查我的示例数据库的附件。

function queryLocations(){  
var ref = firebase.database()
                  .ref('user-locations/' + currentUID)
                  .orderByChild('timestamp')
                  .startAt('1501061958000')
                  .endAt('1501062154000')
                  .on("child_added",function(data){
                       c = c+1;
                       locationCountElement.textContent = '' + c;
                  });
firebaseLocRef = ref;
}

所以,我输入了 startTimestampendTimestamp。我只需要timestampstartTimestampendTimestamp 之间的行。

我的 Firebase 规则如下所示

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "user-locations":{
      "$uid": {
         ".indexOn": "timestamp"
       }
    } 
  }
}

【问题讨论】:

    标签: javascript html firebase firebase-realtime-database


    【解决方案1】:

    你需要startAt()endAt()

    var query = firebase.database()
                        .ref('user-locations/' + currentUID)
                        .orderByChild('timestamp')
                        .startAt(startTimestamp)
                        .endAt(endTimestamp)
                        .on("child_added", function(data) {
    

    更新:在更新后的代码中,您将时间戳作为字符串传递。但在数据库中,它们以数字形式存储,因此您还必须在查询中使用数字:

                  .startAt(1501061958000)
                  .endAt(1501062154000)
    

    【讨论】:

    • 我试过这个。没运气。请检查我更新的问题。
    • 如何索引时间戳? Firebase 查询需要将其编入索引。
    【解决方案2】:

    在此处使用此链接:https://firebase.google.com/docs/database/web/read-and-write

    它很好地概述了如何从数据库中读取数据。

    本质上,您将对数据库进行快照,并搜索具有特定时间戳的所有条目。

    var userId = firebase.auth().currentUser.uid;
    return firebase.database().ref('location_to_timestamp' + userId).once('value').then(function(snapshot) {
      for i in snapshot.val()
         var TS = snapshot.val()[i].timestamp
         if(TS >= startTimestamp && TS <= endTimeStamp) {
           //do stuff to process snapshot.val()[i]
         } 
    }); 
    

    【讨论】:

    • 虽然这可能会给出您想要的结果,但它会从数据库中读取所有数据并在客户端执行过滤。充其量这将是次优的,但在最坏的情况下它可能会浪费大量用户的带宽。
    • 这只是查询所有数据并手动过滤。这需要几分钟的时间来读取数据库并浪费带宽。
    猜你喜欢
    • 2011-11-11
    • 2019-04-26
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多