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"]
}
}
}
}
Author by
Moemanchu
Updated on June 30, 2022Comments
-
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 ofstats
? Do I have to restructure or flatten my data? -
Moemanchu over 9 yearsSo 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 over 9 yearsYou'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 over 9 yearsOkay; 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 over 8 yearscomplete query is
new Firebase(...).child('dinosaurs').orderByChild('height').equalTo(4).on(...)
-
Nicolas Janel over 8 yearsanyway 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 over 8 yearsThis answer is out of data, Firebase now supports deep indexing (see my answer)
-
akshay about 8 yearsI am getting error . Uncaught Error: Query.orderByValue failed: Was called with 1 argument. Expects none.(…)
-
SpiderWasp42 almost 8 years@akshay try .orderByChild('stats/height')