【问题标题】:"error": "Index not defined, add ".indexOn""error": "索引未定义,添加 ".indexOn"
【发布时间】:2016-04-30 08:01:54
【问题描述】:

我在 Firebase 中创建了一个数据库,如下所示:

现在我进入一个 REST 客户端并发出以下查询:

https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&startAt=25&print=pretty

它给了我一个错误:

"error": "Index not defined, add ".indexOn": "age", for path "/movieLens/users", to the rules"

所以我进入规则部分并定义这条规则:

{
    "rules": {
        "users" : {
          ".indexOn": ["age", "gender", "occupation", "zipCode"]
        },
        ".read": true,
        ".write": true
    }
}

但我仍然遇到同样的错误。

【问题讨论】:

    标签: firebase firebase-realtime-database firebase-security


    【解决方案1】:

    您正在为/users 定义索引。树根下没有子节点users,因此这些索引将为空。

    您正在查询/movieLens/users,因此应该在此处定义索引:

    {
        "rules": {
            "movieLens": {
                "users" : {
                    ".indexOn": ["age", "gender", "occupation", "zipCode"]
                },
                ".read": true,
                ".write": true
            }
        }
    }
    

    更新 cmets 中的问题:

    您将用户的年龄存储为字符串,因此无法将其过滤为数字。解决方案是修复您的数据并将其存储为数字。

    但与此同时,这个查询有些工作:

    https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&equalTo="35"
    

    在 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); 
      })
    

    “有点”是它进行词汇排序,而不是数字排序。修复数据以获得真正的解决方案。

    请注意,您也忽略了 Firebase 最佳做法,将数据存储为数组。这已经在 REST API 中给我造成了问题,这就是我放弃 print=pretty 的原因。我强烈建议您从头到尾阅读Firebase programming guide for JavaScript developers 并遵循其中的建议。现在只需几个小时,就可以避免很多小时的问题。

    【讨论】:

    • 它解决了问题,但查询https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&startAt=25&print=pretty 没有过滤任何内容。它返回所有记录
    • 您将年龄存储为字符串。不是一个好主意。我还认真考虑创建自定义索引(只是您维护的查找列表),因为如果没有这些,您将很快遇到性能问题。请参阅这篇博文:firebase.com/blog/2013-04-12-denormalizing-is-normal.html 和这篇文章:highlyscalable.wordpress.com/2012/03/01/…
    猜你喜欢
    • 2015-03-19
    • 2020-02-22
    • 1970-01-01
    • 2018-06-16
    • 2012-12-08
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    相关资源
    最近更新 更多