chicobermuda chicobermuda - 2 months ago 22
Swift Question

Firebase: Searching child nodes that have a unique ID

I'm fairly new to Firebase and have a rankings app, where my structure currently looks like the following:

{
"Rankings" : {
"-KFGX5H3rLSnpPvupakm" : {
"Sports Teams" : {
"Red sox" : 1,
"Warriors" : 3,
"Yankees" : 2
}
},
"-KFGZkwAIl817CLDLmMp" : {
"Beers" : {
"Bud light" : 3,
"Coors" : 2,
"Pbr" : 4
}
}
}
}


I'm using childIDs so I can sort these chronologically. If I want to search rankings by name, how can I bypass the child ID to do so?

For instance, if a user searches for rankings using the term "Sports," how can I traverse my
Rankings
tree by searching for all rankings containing "Sports"?

Answer

This type of deep querying on dynamic paths is not possible with Firebase (nor with many other NoSQL databases). What you'll need to do is set up a so-called index, that maps the keys that you want to search for to the values that you want to find.

{
  "Rankings" : {
    "-KFGX5H3rLSnpPvupakm" : {
      "Sports Teams" : {
        "Red sox" : 1,
        "Warriors" : 3,
        "Yankees" : 2
      }
    },
    "-KFGZkwAIl817CLDLmMp" : {
      "Beers" : {
        "Bud light" : 3,
        "Coors" : 2,
        "Pbr" : 4
      }
    }
  },
  "SearchTerms": {
        "Red sox" : {
          "-KFGX5H3rLSnpPvupakm": true
        },
        "Warriors" : {
          "-KFGX5H3rLSnpPvupakm": true
        },
        "Yankees" : {
          "-KFGX5H3rLSnpPvupakm": true
        },
        "Bud light" : {
          "-KFGZkwAIl817CLDLmMp": true
        },
        "Coors" : {
          "-KFGZkwAIl817CLDLmMp": true
        },
        "Pbr" : {
          "-KFGZkwAIl817CLDLmMp": true
        }
  }
}

This process is called denormalizing your data and it's described in this blog post, in the Firebase documentation on structuring data and in this article on NoSQL data modeling. And in probably half a dozen similar answers I've given recently.

Comments