2017-07-27 79 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