Reputation: 31546
I have created a database in Firebase which looks like:
Now I go into a REST client and issue this query:
https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&startAt=25&print=pretty
It gives me an error:
"error": "Index not defined, add ".indexOn": "age", for path "/movieLens/users", to the rules"
So I go in the rule section and define this rule:
{
"rules": {
"users" : {
".indexOn": ["age", "gender", "occupation", "zipCode"]
},
".read": true,
".write": true
}
}
But I still get the same error.
Upvotes: 46
Views: 22911
Reputation: 599491
You're defining indexes for /users
. There is no child node users
straight under the root of your tree, so those indexes will be empty.
Since you query /movieLens/users
, that's exactly where the index has to be defined:
{
"rules": {
"movieLens": {
"users" : {
".indexOn": ["age", "gender", "occupation", "zipCode"]
},
".read": true,
".write": true
}
}
}
Update for problem in the comments:
You're storing the user's age as a string, so cannot filter them as a number. The solution is to fix your data and store it as a number.
But in the meantime this query somewhat works:
https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&equalTo="35"
In JavaScript:
ref
.orderByChild('age')
.startAt('35')
.limitToFirst(3)
.once('value', function(s) {
console.log(JSON.stringify(s.val(), null, ' '));
}, function(error) {
if(error) console.error(error);
})
The "somewhat" being that it does a lexical sort, not a numerical one. Fix the data for a real solution.
Note that you're also ignoring Firebase guidance on structuring data by storing the data as an array. This was already causing problems for me in the REST API, which is why I dropped the print=pretty
. I highly recommend that you read the Firebase programming guide for JavaScript developers from start to finish and follow the advice in there. The few hours that takes now, will prevent many hours of problems down the line.
Upvotes: 52