0

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"
Community
  • 1
  • 1
juergen d
  • 201,996
  • 37
  • 293
  • 362

1 Answers1

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"
    }
  }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807