Firebase sorting/filtering with keys node

2019-07-29 05:38发布

问题:

{
"places": {
    "<push-key>": {
        "name": "Company X"
    },
    "<push-key>": {
        "name": "Restaurant Y"
    }
}
"stamps": {
    "<push-key>": {
        "value": 0,
        "date": 1487344650456
    }
},
"placeStamps": {
    "<place-push-key>": {
        "<stamp-push-key-1>": true,
        "<stamp-push-key-2>": true,
        "<stamp-push-key-3>": true
    }
}
}

We are new to Firebase and we were wondering if there was a way to sort our stamps (node in the database) by date. Our flow goes as following:

  • We retrieve the place that we want, using the places node.
  • With the key of the place we retrieve the stamp keys from the placeStamps/ node.
  • Then we retrieve the stamps one-by-one from the stamps node.

Is there a way to sort/filter these objects by for example the ‘date’ or ‘value’? We can’t do it client-side, because we are talking about millions of stamps.

回答1:

To query the stamps since 24 hours ago:

var ref = firebase.database.ref("stamps");
var now = Date.now();
var yesterday = now - 24 * 60 * 60 * 1000;
var query = ref.orderByChild("Date").startAt(yesterday);
query.on("child_added", function(snapshot) {
    console.log(snapshot.key);
});

If you want to retrieve the stamps for a certain place by timestamp, you have two options:

  • retrieve the stamps for the place and order them by timestamp client-side. Retrieving multiple items is not as slow as you may expect, since Firebase pipelines the requests. See Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly.
  • add the timestamp to the stamp key for each place:

    placeStamps": {
      "<place-push-key>": {
        "<stamp-push-key-1>": 1487344650456,
        "<stamp-push-key-2>": 1487344650457,
        "<stamp-push-key-3>": 1487344650458
      }
    }
    

    Now you can get the stamps for a place by timestamp with:

    var ref = firebase.database.ref("placeStamps").child("<place-push-key>");
    var now = Date.now();
    var yesterday = now - 24 * 60 * 60 * 1000;
    var query = ref.orderByValue().startAt(yesterday);