Edward Hung Edward Hung - 5 months ago 37
Swift Question

firebase .indexOn warning with autoId

I am using firebase to store some data. When I use queryOrderedByChild("count"), I get the following warning

Using an unspecified index. Consider adding ".indexOn": "count" at /comments/-KM449ubmviUkGNIj2fq to your security rules for better performance

My firebase structure looks like this

"comments" : {
"-KM449ubmviUkGNIj2fq" : {
"-KM44Ax8MdcBBPT_BQiO" : {
"count" : 3,
"comment" : "a",
"commentOwner" : "hakV4smGyveurPhFN7g9rad4xsP2",
"date" : "1467890319.38933"
},
"-KM45-Eb6yvXSAfhBrLX" : {
"count" : 2,
"comment" : "b",
"commentOwner" : "hakV4smGyveurPhFN7g9rad4xsP2",
"date" : "1467890533.56065"
},
"-KM488JCKddZhbev466U" : {
"count" : 4,
"comment" : "c",
"commentOwner" : "hakV4smGyveurPhFN7g9rad4xsP2",
"date" : "1467891357.06534"
},
"-KM48SXJ83L7-mpE5nma" : {
"count" : 0,
"comment" : "d",
"commentOwner" : "hakV4smGyveurPhFN7g9rad4xsP2",
"date" : "1467891439.88917"
},
"-KM4AN_rj-ycRZYESnh_" : {
"count" : 0,
"comment" : "e",
"commentOwner" : "hakV4smGyveurPhFN7g9rad4xsP2",
"date" : "1467891944.01086"
},


Basically, I want to generate a list of firebase snapshots with the highest number of counts (similar to number of likes).

Since my post and comments have their unique Ids generated from firebase, I am not sure what I should do in terms of indexing to eliminate the warning.

I have tried the following security rule and it does not work

"rules": {
".read": "auth != true",
".write": "auth != true",
"comments" : {
".indexOn" : ["count"]
}


}

Thanks

Answer

Most likely you are trying to query the comments for a specific post.

In that case you need to tell the database to index the comments for each post. The syntax for that is:

"rules": {
  ".read": "auth != true",
  ".write": "auth != true",
  "comments" : {
    "$commentId": {
      ".indexOn" : ["count"]
    }
  }
}

With this you can order the comments for a specific post by the value of their count property.