Firebase .indexOn dynamic keys

China☆狼群 提交于 2020-01-10 04:14:07

问题


I've started testing Firebase and I can't figure out one thing about indexing. I'm creating a structure based on what I've read on - Firebase Data Structuring - something like that example with Users and Groups. JSON tree looks something like this:

{
  "babies" : {
    "-KQSVCXI-ZMz_lQ_Q906" : {
      "name" : "Baby",
      "parents" : {
        "F0o8Gr5GC2SrakUYZpC20efcmk63" : true
      }
    },
    "-KQSf4t9XQC3LnbsxLYS" : {
      "name" : "Name2",
      "parents" : {
        "S6aO6Dx4lgg6anW9S9hu7EJrhVg1" : true
      }
    }
  }
}

and I'm trying to get babies for a parent - just like there were members in groups in a Firebase example. I'm doing that in the iOS Application by using:

self.babiesReference
                .queryOrderedByChild("parents/\(user.uid)")
                .queryEqualToValue(true)
                .observeSingleEventOfType(.Value, withBlock: { (snapshot) in

                // Print value
                print(snapshot.value)

            }

where user.uid is current user's id. This works fine but the only problem that remains is this:

Using an unspecified index. Consider adding ".indexOn": "parents/S6aO6Dx4lgg6anW9S9hu7EJrhVg1" at /babies to your security rules for better performance

How to index this "dynamic" child presented by user's id? Is there a way to do it or must I change the tree structure?

Thanks.


回答1:


For this type of query (and in general when you get into requiring adding indexes dynamically) you'll likely need to set up an inverted index. In your case:

{
  "babies" : {
    "-KQSVCXI-ZMz_lQ_Q906" : {
      "name" : "Baby",
      "parents" : {
        "F0o8Gr5GC2SrakUYZpC20efcmk63" : true
      }
    },
    "-KQSf4t9XQC3LnbsxLYS" : {
      "name" : "Name2",
      "parents" : {
        "S6aO6Dx4lgg6anW9S9hu7EJrhVg1" : true
      }
    }
  },
  "parents": {
    "F0o8Gr5GC2SrakUYZpC20efcmk63": {
      "babies": {
        "-KQSVCXI-ZMz_lQ_Q906": true
      }
    },
    "S6aO6Dx4lgg6anW9S9hu7EJrhVg1": {
      "babies": {
        "-KQSf4t9XQC3LnbsxLYS": true
      }
    }
  }
}

This type of bidirectional linking is fairly common in Firebase (and in many similar NoSQL databases).



来源:https://stackoverflow.com/questions/39238374/firebase-indexon-dynamic-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!