0

I have this structure:

conversations:
   -439f6b3c0958:
        -messages:...
            -users:
                -ccb756c0:
                     -userId: ccb756c0
                     ...

I'm trying to query the conversations by userId inside of the conversation/{someid}/users node

Firebase sdk is giving me this warning and its very bad for performance

 Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding '".indexOn": "users/ccb756c0/userId"' at conversations to your security and Firebase Database rules for better performance

I added this rule but it didn't solve the problem

"conversations": {
    "$conversationId":{
          "users" :{
                "$uid":{
                  "userId": {".indexOn": ".value"}
                  }
          }
    }
}

I also tried this with no luck:

"conversations": {
    "$conversationId":{
          "users" :{
                "$uid":{
                  ".indexOn": "userId"
                  }
          }
    }
}

Who shouldI write this rule to match the structure i'm using?

MtziSam
  • 130
  • 11

1 Answers1

1

You need to define indexes on the level where run the query. Right now you have it one level too low.

So it should be:

"conversations": {
    "$conversationId":{
          "users" :{
              "userId": {".indexOn": ".value"}
          }
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • This also doesn't seem to work, so maybe the problem is the query i'm using? `firebaseConversationssReferance.orderByChild("users/"+userId+"/userId").equalTo(userId).addValueEventListener...` , is appending the useId messing with the rule? – MtziSam Apr 20 '20 at 18:46
  • 1
    The `.indexOn` values must point to the exact path under each child node of the value to index. You have a wildcard/dynamic value in there, which isn't possible. You'll typically need to create an inverted index in the JSON yourself to allow this. See https://stackoverflow.com/questions/27207059/firebase-query-double-nested and https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value – Frank van Puffelen Apr 20 '20 at 20:40
  • 1
    My other way of phrasing this is that your current data structure makes it easy to find the users for a conversation. It does not however make it easy to find the conversations for a user. To allow that, you'll want to add an inverted data structure, where you start with `/user_conversations/$uid/$conversationId`. – Frank van Puffelen Apr 20 '20 at 20:42
  • I ended up adding the lookup/indexing node to the database and modifying the lookup logic, it seems to be working ok with small data size and will stress test it for scalability which were my original method before. Thanks for the great help @Frank – MtziSam Apr 20 '20 at 23:07