【问题标题】:Firebase Realtime Database - index on location containing uidFirebase 实时数据库 - 包含 uid 的位置索引
【发布时间】:2019-08-31 08:35:06
【问题描述】:

我正在尝试通过按照控制台日志中的建议创建索引来提高 Firebase 实时数据库的性能。大多数建议很容易遵循,但不是全部。

我现有的规则:

"notes": {
  ".indexOn": ["data/title", "access/author"],
  ".read": "
    auth.uid !== null 
  ",
  "$note_id": {
    ".write": "
      (!data.exists() && auth.uid !== null) ||
      (
        data.child('access').child('author').val() === auth.uid 
      ||
        data.child('access/members').child(auth.uid).exists()
      )
    ",
    "data": {
      ".read": "
        data.parent().child('access').child('author').val() === auth.uid ||
        data.parent().child('access/members').child(auth.uid).exists()
      ",
      ".write": "
        data.parent().child('access').child('author').val() === auth.uid ||
        data.parent().child('access/members').child(auth.uid).exists()          
      ",
    "access" : {
      ".read" : "
        (auth.uid !== null) &&
        (
          data.child('author').val() === auth.uid
          ||
          data.child('members').child(auth.uid).exists()
        )
      ",
    "members" :{
        ".write" : "
          (!data.exists() && auth.uid !== null) ||
          data.parent().child('author').val() === auth.uid ||
          data.parent().child(auth.uid).exists()
        "
      }
    }
  }
},

一些建议适用于以用户 uid 结尾的位置 - 类似于以下控制台日志:

FIREBASE 警告:使用未指定的索引。

考虑在 /notes 添加 ".indexOn": "access/members/3weT1tYhG456HH0CuC45Muc44ax6" 符合您的安全规则以获得更好的性能

是否可以在 Firebase 实时数据库中添加此索引规则 - 考虑到位置位置以用户 uid 字符串结尾?

【问题讨论】:

    标签: firebase firebase-realtime-database


    【解决方案1】:

    您当前的数据结构可以轻松找到特定笔记的成员。查找特定成员的注释并不容易。为了允许第二个用例并确保它是可扩展的,您需要添加一个额外的数据结构:

    user_notes: {
      user_id_1: {
        note_id1: true,
        note_id2: true,
        note_id3: true
      },
      user_id_2: {
        note_id3: true,
        note_id4: true,
        note_id5: true
      }
    }
    

    通过这种附加结构,您无需查询即可确定用户可以访问哪些节点。

    这当然意味着当您允许用户访问笔记时,您需要写入两个位置,但这是非常常见且可扩展的,并且仍然可以通过规则来保护。

    另见:

    【讨论】:

    • 感谢@frank 的及时回复和很好的回答! :) 这似乎是一个足够简单的解决方案。我已经有数据库监听器来完成这项工作。现在我只是想知道如何以有效的方式获取这些注释(不仅仅是 id)?
    • 顺便说一句 - 您是否建议从客户端同时(原子)写入数据以更新 user_notes 节点或使用数据库侦听器?
    • 获取具有上述结构的实际节点意味着您将为每个节点使用once() 侦听器。这并不像您最初想象的那么慢,因为 Firebase pipelines the requests over a single connection。当然,你也可以在这两个地方写下整个笔记,这会复制数据,但会使读取更简单、更快。
    猜你喜欢
    • 1970-01-01
    • 2021-03-01
    • 2020-08-24
    • 1970-01-01
    • 2020-12-07
    • 2021-08-24
    • 2020-05-08
    • 2020-08-25
    • 2017-10-06
    相关资源
    最近更新 更多