cbradshaw
cbradshaw

Reputation: 58

Good Approach to Sort and Filter in Conjunction - Firebase Realtime Database Structure

I'm working on setting up a realtime database for Firebase and have run into a question which is making me question my database structure. My current structure is as follows:

{
"events": {
    $topics:{
        $eventID:{
            "title": "testTitle",
            "description": "testDescription",
            "startDateTime": "testStartDateTime",
            "lat": "testLat",
            "lng": "testLng",
            "voteCt": "testVoteCt"
        }
    }
}

The idea behind this is that I can easily filter data based on topic. The problem I have is when I want to get events from all $topics sorted by startDateTime. From what I've read, this is not possible with this given structure. If this is not the case, please somebody correct me.

Alternatively, I have consider structuring my events as follows:

{
"events": {
    $eventID:{
          "title": "testTitle",
          "description": "testDescription",
          "startDateTime": "testStartDateTime",
          "lat": "testLat",
          "lng": "testLng",
          "voteCt": "testVoteCt",
          "topic": "testTopic"
        }
}

With this approach I can aggregate all of my events when sorting by startDateTime but I can't also filter by topic when I sort by startDateTime. My last hope is just having the client read in all of the events (large amount of data) and loop through only displaying those with the topic matching the applied filter. That solution works but its a lot of work to do something that seems so simple.

Can anybody think of a better solution? Thanks.

Upvotes: 3

Views: 80

Answers (1)

Tim
Tim

Reputation: 404

How about this structure:

 "events": {
        $eventID:{
              "title": "testTitle",
              "description": "testDescription",
              "startDateTime": "testStartDateTime",
              "lat": "testLat",
              "lng": "testLng",
              "voteCt": "testVoteCt",
              "topic": "testTopic"
          }
  }

    "event_topic":{
           "testTopic1": {
                  "event_topic_id1":{
                       "event": "event id 1"
                      "startDateTime":"testStartDateTime"

                   }
           }
     }

Now if you want to query testTopic1 and sort by startDateTime, just listen to event_topic/testTopic1 and order child by startDateTime with on child_add, and for each on child_add event, use the event id to query the event detail.

Upvotes: 1

Related Questions