Sundeep1501
Sundeep1501

Reputation: 1538

Firebase request range of rows

I'm storing user's lat, lng, timestamp for every minute. I want to read only portion of data based on timestamp. I've tried below query, didn't work. Also check the attachment of my sample database.

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

So, I've startTimestamp and endTimestamp as input. I need only rows with timestamp between startTimestamp and endTimestamp.

My firebase rules look like this

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

Upvotes: 0

Views: 118

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599661

You need startAt() and endAt():

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

Update: in your updated code you pass the timestamps as strings. But in the database they're stored as numbers, so you must also use numbers in the query:

              .startAt(1501061958000)
              .endAt(1501062154000)

Upvotes: 2

Joe Bernstein
Joe Bernstein

Reputation: 163

Use this link here: https://firebase.google.com/docs/database/web/read-and-write

It has a good overview of how to read from the database.

In essence, you will take a snapshot of the DB, and search for all entries with a certain timestamp.

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]
     } 
}); 

Upvotes: 0

Related Questions