【问题标题】:Firebase: How to add an index for a nested field?Firebase:如何为嵌套字段添加索引?
【发布时间】:2017-03-23 13:15:24
【问题描述】:

我有一个locations-orders 表,如下所示:

{
  "0BW3H9T3R7HJB" : {
    "orders" : {
      "01750ea0-4980-4bc4-58b2-988c02324e671478636582396" : {
        "created_at" : 1478636560000,
      },
      "01750ea0-4980-4bc4-58b2-988c02324e671478636582483" : {
        "created_at" : 1478636560000,
      }
    }
}

每个 location-orders 节点都有一个 orders 节点,其中包含多个键/对象。这些对象上有一个created_at 字段。

我将此添加到我的数据库规则中:

{
  "rules": {
    ".read": true,
    ".write": true,
    "users": {
      ".indexOn": "merchantId"
    },
    "merchants": {
      ".indexOn": "locations"
    },
    "locations-orders": {
      ".indexOn": ["orders/created_at"]
    }
  }
}

但是,Firebase 仍然抱怨我缺少索引:

Using an unspecified index. Consider adding ".indexOn": "created_at" at /locations-orders/1JS53G0TT5ZQD/orders to your security rules for better performance

我应该运行一些东西来创建索引吗?还是写错了?

=== 更新 ===

我更改了我的文件以查看:

{
  "rules": {
    ".read": true,
    ".write": true,
    "users": {
      ".indexOn": "merchantId"
    },
    "merchants": {
      ".indexOn": "locations"
    },
    "locations-orders": {
      "$location_id": {
        ".indexOn": ["orders/created_at", "orders/status_updated_at"]
      }
    }
  }
}

但我仍然收到相同的警告:

Using an unspecified index. Consider adding ".indexOn": "created_at" at /locations-orders/1JS53G0TT5ZQD/orders to your security rules for better performance

【问题讨论】:

  • 您在问题中包含了 JSON 树和规则的图片。请将这些替换为实际的 JSON 和文本规则,您可以通过单击 Firebase 数据库控制台中的导出按钮轻松获取这些内容。将 JSON 作为文本使其可搜索,让我们可以轻松地使用它来测试您的实际数据并在我们的答案中使用它,一般来说这只是一件好事。
  • 肯定会的!!!
  • @FrankvanPuffelen 更新!

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


【解决方案1】:

试试这个:

{
  "rules": {
    ".read": true,
    ".write": true,
    "users": {
      ".indexOn": "merchantId"
    },
    "merchants": {
      ".indexOn": "locations"
    },
    "locations-orders": {
      "orders": {
        "$orderid": {
          ".indexOn": "created_at"
        }
      }
    }
  }
}

【讨论】:

    【解决方案2】:

    如果你看一下你的数据结构,/location-order/$orderId下面没有orders/created_at

    {
      "rules": {
        ".read": true,
        ".write": true,
        "users": {
          ".indexOn": "merchantId"
        },
        "merchants": {
          ".indexOn": "locations"
        },
        "locations-orders": {
          "$someid": {
            ".indexOn": ["orders/created_at"]
          }
        }
      }
    }
    

    【讨论】:

    • 我为$someid写什么重要吗?
    • 不。它就像您实际代码中的变量名:只要您在规则中使用相同的值(此处不需要),实际名称无关紧要。
    • 我不需要运行任何命令或任何东西?我更新它看起来像这样,但它仍然显示错误
    • 索引会在您保存定义它们的规则时立即创建。如果您仍然遇到问题:您可以在最小的 jsbin 中重现它们吗?这将更容易获得完整的图片。
    猜你喜欢
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 2022-07-02
    • 2014-12-14
    • 2021-12-11
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多