Using .indexOn with nested keys in Firebase

13,681

Solution 1

You can query and index arbitrarily deep now.

{
  "rules": {
    "$dinosaur": {
      ".indexOn": ["stats/height"]
    }   
  }
}

and query on nested values:

.orderByChild('stats/height')

Solution 2

Update 2015/12/17: Firebase now supports deep indexing, so see Tom's answer.


You can arbitrarily nest indexing rules in your data tree, though you can only query the attributes of one list of elements at a time - not arbitrary deep. Here's some example rules, to index height:

{
  "rules": {
    "$dinosaur": {
      "stats": {
        ".indexOn": ["height"]
      }
    }   
  }
}
Share:
13,681
Moemanchu
Author by

Moemanchu

Updated on June 30, 2022

Comments

  • Moemanchu
    Moemanchu about 2 years

    I have a a bunch of keys that i want to index using .indexOn

    Suppose my data looks like the following. I want to be able to use .orderByChild("height").

    {
      "lambeosaurus": {
        "stats": {
          "height" : 2.1,
          "length" : 12.5,
          "weight": 5000
        }
      },
      "stegosaurus": {
        "stats": {
          "height" : 4,
          "length" : 9,
          "weight" : 2500
        }
      }
    }
    

    How wound I specify the rule for indexing height which is a child of stats? Do I have to restructure or flatten my data?

  • Moemanchu
    Moemanchu over 9 years
    So how would I query this? I tried setting up the query with something like the following but nothing get's returned. Thanks for your help. var fb = new Firebase("https://a_fb_ur./dinosaur"); fbQuery = fb.orderByChild("height").equalTo(4);
  • Rob DiMarco
    Rob DiMarco over 9 years
    You'll have to flatten your data in order to do that query, and then you need to attach a listener to retrieve data. i.e. new Firebase(...).child('dinosaurs').orderByChild('height').on('‌​child_added', function(snapshot) { ... }).
  • Moemanchu
    Moemanchu over 9 years
    Okay; For storing GeoJSON I'll probably want to flatten the data then cause I'll commonly want to index and search on keys stored in the nested "properties" key. Thanks for confirming.
  • Nicolas Janel
    Nicolas Janel over 8 years
    complete query is new Firebase(...).child('dinosaurs').orderByChild('height').equa‌​lTo(4).on(...)
  • Nicolas Janel
    Nicolas Janel over 8 years
    anyway the Firebase doc doesn't give exemple of wildcard node applied on indexes, as it applied in security rules, it's logical it works for indexes too. Thanks to get the idea
  • Tom Larkworthy
    Tom Larkworthy over 8 years
    This answer is out of data, Firebase now supports deep indexing (see my answer)
  • akshay
    akshay about 8 years
    I am getting error . Uncaught Error: Query.orderByValue failed: Was called with 1 argument. Expects none.(…)
  • SpiderWasp42
    SpiderWasp42 almost 8 years
    @akshay try .orderByChild('stats/height')