javascript - Firebase retrieve data by key -
i have firebase node follows -
providers -userid1 --userid : userid1 --keywords ---key1 : true ---key2 : true ---key3 : true -userid2 --userid : userid2 --keywords ---key1 : true ---key4 : true ---key5 : true
i want retrieve userids have "key1" in keywords child.
i tried following query
var ref = new firebase(url+"/providers") ref.orderbychild("keywords").equalto("key1").on("value", function(snapshot){ console.log(snapshot.numchildren()); })
also tried -
var ref = new firebase(url+"/providers") ref.orderbykey().equalto("key1").on("value", function(snapshot){ console.log(snapshot.numchildren()); })
i no results. missing in query? how above 2 queries different? both queries don't work.
your key1
key, while equalto()
used check values.
the trick query records key1
key has value of true
:
var ref = new firebase(url+"/providers") ref.orderbychild("keywords/key1").equalto(true).on("value", function(snapshot){ console.log(snapshot.numchildren()); })
don't forget add indexes on keywords/key1
, etc. rules.json:
"providers": { "$uid": { ".indexon": ["keywords/key1", "keywords/key2", "keywords/key3", "keywords/key4", "keywords/key5"] } }
you'll find adding such indexes unmaintainable, indication data structure should improved. in case, can done adding secondary, inverted index maps each specific key matching providers:
providers userid1 userid : userid1 keywords key1 : true key2 : true key3 : true userid2 userid : userid2 keywords key1 : true key4 : true key5 : true providers_by_keyword: key1: userid1: true userid2: true key2: userid1: true key3: userid1: true key4: userid2: true key5: userid2: true
now can execute both operations without query:
- get keywords
user1
:ref.child('users/user1/keywords').on(...
- get users
key1
:ref.parent().child('providers_by_keyword/key1').on(...
this approach of creating secondary indexes known denormalizing in nosql databases. described in firebase's denormalizing normal blog post. recommend reading article nosql data modeling.
Comments
Post a Comment