2017-07-27 35 views
0

我每分钟都会存储用户的lat, lng, timestamp。 我想根据timestamp只读取部分数据。我试过下面的查询,没有工作。同时检查我的示例数据库的附件。Firebase请求的行数范围

enter image description here

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之间的行。

我火力的规则是这样的

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

回答

2

你需要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) 
+0

我试过这个。没有运气。请检查我更新的问题。 – Sundeep1501

+0

如何索引时间戳? Firebase查询需要将其编入索引。 – Sundeep1501

+0

查看我的更新回答 –

0

使用此链接在这里: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] 
    } 
}); 
+0

虽然这可能会给出您想要的结果,但它会读取数据库中的所有数据并执行过滤客户端。充其量,这将是次优的,但最糟糕的是它可能会浪费很多用户的带宽。 –

+0

这只是查询所有数据并手动过滤。这需要几分钟的时间来读取数据库和浪费带宽。 – Sundeep1501