分享
三行代码  ›  专栏  ›  技术社区  ›  Dan.code

Firebase安全规则继续要求“考虑添加”.indexOn“:”即使在添加了indexOn之后

  •  1
  • Dan.code  · 技术社区  · 1 周前

    代码如下:

        func searchUser(search: String, includeCurrentUser: Bool = true, completion: @escaping ([User]) -> (), withCancel cancel: ((Error) -> ())?) {
            Database.database().reference().child("users").queryOrdered(byChild:  "username").queryStarting(atValue: search , childKey: "username").queryEnding(atValue: search + "\u{f8ff}", childKey: "username").observeSingleEvent(of: .value, with: { (snapshot) in
                    guard let dictionaries = snapshot.value as? [String: Any] else {
                    completion([])
                    return
                }
                var users = [User]()
                dictionaries.forEach({ (key, value) in
                    if !includeCurrentUser, key == Auth.auth().currentUser?.uid {
                        completion([])
                        return
                    }
                    guard let userDictionary = value as? [String: Any] else { return }
                    let user = User(uid: key, dictionary: userDictionary)
                    users.append(user)
                })
                
                users.sort(by: { (user1, user2) -> Bool in
                    return user1.username.compare(user2.username) == .orderedAscending
                })
                completion(users)
                
                
            }){ (err) in
                print("Failed to fetch all users from database:", (err))
                cancel?(err)
            }
        }
    

    [Firebase/Database][I-RDB034028]使用未指定的索引。您的数据将在客户端下载和过滤。考虑将“.indexOn”:“username”at/users添加到安全规则中以获得更好的性能

    以下是我的firebase规则:

    {
      /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
      "rules": {
        ".read": true,
        ".write": true,
        "posts" : {
            ".indexOn": "creationDate"
        },
        "purchaser" : {
            "$postID" : {
             ".indexOn": ".value"
          }
        },
          "users" : {
            "$uid": {
                ".indexOn" : "username"
            }
          }
        }
        }
    

    enter image description here

    所以searchUser函数可以工作,但是xcode控制台继续要求.indexOn输入用户名。

    为什么这里出了问题?

    1 回复  |  直到 1 周前
        1
  •  1
  •   Frank van Puffelen    1 周前

    需要在您所在的位置定义索引 使用 /users username 每个子节点的属性:

      "users" : {
        ".indexOn" : "username"
      }