44

I have created a database in Firebase which looks like:

database structure

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.

Grimthorr
  • 6,856
  • 5
  • 41
  • 53
Knows Not Much
  • 30,395
  • 60
  • 197
  • 373

1 Answers1

47

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    it solves the problem but the query `https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&startAt=25&print=pretty` doesn't filter anything. it returns all the records – Knows Not Much Jan 24 '16 at 00:42
  • 1
    You're storing your age as a string. Not a good idea. I'd also *seriously* consider creating custom indexes (just lookup lists that you maintain), because you'll run into performance problems quickly without those. See this blog post: https://www.firebase.com/blog/2013-04-12-denormalizing-is-normal.html and this article: https://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/ – Frank van Puffelen Jan 24 '16 at 01:48