如何在firebase中设置.indexOn?

时间:2019-06-07 09:30:53

标签: firebase firebase-realtime-database

这是我的json结构

{
      "books" : {
        "sample" : {
          "eight" : {
            "author" : "eighta",
            "name" : "eight",
            "sub" : {
              "subauthor" : "eightauthor",
              "subname" : "general"
            }
          },
          "eleven" : {
            "author" : "twelvea",
            "name" : "twelve",
            "sub" : {
              "subauthor" : "elevenauthor",
              "subname" : "general"
            }
          },
          "five" : {
            "author" : "fivea",
            "name" : "five",
            "sub" : {
              "subauthor" : "fiveauthor",
              "subname" : "fivesub"
            }
          },
          "four" : {
            "author" : "foura",
            "name" : "four",
            "sub" : {
              "subauthor" : "fourauthor",
              "subname" : "general"
            }
          },
          "nine" : {
            "author" : "ninea",
            "name" : "nine",
            "sub" : {
              "subauthor" : "nineauthor",
              "subname" : "ninesub"
            }
          },
          "one" : {
            "author" : "onea",
            "name" : "one",
            "sub" : {
              "subauthor" : "oneauthor",
              "subname" : "onesub"
            }
          },
          "seven" : {
            "author" : "seven",
            "name" : "seven"
          },
          "six" : {
            "author" : "sixa",
            "name" : "six"
          },
          "ten" : {
            "author" : "tena",
            "name" : "ten"
          },
          "three" : {
            "author" : "threea",
            "name" : "three"
          },
          "two" : {
            "author" : "twoa",
            "name" : "two"
          }
        }
      }
    }

我想获取子名称等于一般名称的数据

我的索引规则

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    ".read": true,
    ".write": true,
      "books": {
        "$user_id": {
          ".indexOn": ["subname", "subauthor"]
        }
        }
      }
  }
}

https://myprojectpath/books/sample/eight.json?orderBy="subname"&equalTo="general"&print=pretty

以上规则运行正常。但是我需要传递通用api来获取子名称应该是通用的数据。每次调用时,我都无法传递August.json,nine.json和ten.json。我应该只调用一个api来提供子名称应该是通用的数据。

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,那么您想使用一个查询在所有作者中搜索其sub/subname属性。

在这种情况下,您可以在books/sample上为每个子节点的sub/subname属性定义一个索引:

"books": {
    "sample": {
        ".indexOn": ["sub/subname", "sub/subauthor"]
    }
}

sample可能是此处的$变量(例如$user_id),但是.indexOn中的路径必须是已知的。

这将在sample下为每个子节点创建一个值为sub/subname的索引,然后可以使用以下查询:

https://myprojectpath/books/sample.json?orderBy="sub/subname"&equalTo="general"&print=pretty