0

Say if I have my data in firebase stored as the following:

{
    "sensor_data": {
      "duration": 41143403,
      "activity": "unknown"
    },
    "sensor_name": "Activity",
    "timestamp": {
      "start_time": "Mon Mar 6 00:00:00 EST 2017",
      "end_time": "Mon Mar 6 11:25:44 EST 2017"
    }
  },

I want to get the duration value within the sensor_data object by entering a string input, comparing that string input to the start_time value within the timestamp object. How is it possible to execute a query as such? does the string input have to match exactly to the start_time value?

AfternoonTiger
  • 357
  • 1
  • 4
  • 10

1 Answers1

3

Firebase can perform range queries, and even do this on strings. But it will compare the values from the start of the string. So in your start_time format that means you can search for all items on Monday March 6 with something like:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference(...);
ref.orderByChild("timestamp/start_time").startAt("Mon Mar 6").endAt("Mon Mar 6~")...

But there's no way to get the child notes from March 6 to 7, since the those start with "Tue Mar 7".

To allow filtering dates in a string format, you have to make sure the date format is the same in lexicographical (alphabetical) order as it is in chronological order. A great string format for that is ISO-8601, which could like like this for the same start_date you have: "2020-03-06T00:00:00-04:00"

On that you could then query for March 6 to 7 with:

ref.orderByChild("timestamp/start_time").startAt("2020-03-06").endAt("2020-03-07~")...

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807