Firebase Realtime DB: Howto index properly on key-value pair

↘锁芯ラ 提交于 2020-01-11 07:43:08

问题


Question

I have this Firebase Realtime Database:

{      
  "groupUsers" : {
    "group1key" : {
      "user1key" : "admin"
    },
    "group2key" : {
      "user1key" : "admin",
      "user2key" : "readonly",
      "user3key" : "readwrite"
    }
  }
}

In my Android app I query that like this

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("groupUsers");
ref.orderByChild(auth.getCurrentUser().getUid()).startAt("").addValueEventListener() {...}

That produces the warning:

Using an unspecified index. Consider adding ".indexOn" ... to your security and Firebase Database rules for better performance

How to index properly? When the data is growing I fear that my app will become super slow querying on not-indexed data.

Background

I already tried in my rules file to index the values:

".indexOn": ".value"

but that would work only if the data are scalars but they are key-value pairs ("user1key" : "admin").

I can't just add an index in my rules file like this:

".indexOn": ["user"]

since that requires a constant property name like this:

{ "groupUsers" : {
    "group1key" : {
      "name" : "user1"
    }        
  }
}

But I have values as names like

"user1key" : "admin",
"user2key" : "readonly",
"user3key" : "readwrite"

回答1:


There is no way to pre-create the indexes for such a structure. I've covered this type of structure in my answer here and here and the new Firestore documentation (which works similarly in this aspect) even has a documentation page about it.

The recommendation is to store data in a way that allows this lookup in the other direction too. With your current structure you can efficiently look up the users in a group. To also allow looking up the groups for a user, add this structure:

{      
  "usersGroups" : {
    "user1key" : {
      "group1key" : "admin",
      "group2key" : "admin"
    },
    "user2key" : {
      "group2key" : "readonly",
    },
    "user3key" : {
      "group2key" : "readwrite"
    }
  }
}


来源:https://stackoverflow.com/questions/48283040/firebase-realtime-db-howto-index-properly-on-key-value-pair

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