Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Database - Add Index on "dynamic" child

I'm using Firebase Database to store the scores of a game. All is working fine until I've decided to implement a "weekly score".

In order to be able to filter by score and then order by weekly, I'm storing the data in the following structure:

game_scores-weekly
    2018-01-29
        user_id: { score, date, bla, bla bla}
        user_id: { score, date, bla, bla bla}
        user_id: { score, date, bla, bla bla}

    2018-02-05
        user_id: { score, date, bla, bla bla}
        user_id: { score, date, bla, bla bla}

So, this works just fine but I get that annoying warning every new week about performance issues due not having indexes on "game_scores-weekly/new_week" indexOn "score". Manually adding the index works... until the next week, so not an option.

    "game_scores-weekly": {
      "2018-02-19": {
        ".indexOn": ["score", "uid"]
      },
      "2018-02-12": {
        ".indexOn": ["score", "uid"]
      }
    } 

Is there any way to specify somehow a wildcard in the date, so it works for any new date? or perhaps can I programatically create the new index every week, or is there any other solution I might have not thought about?

Also, thought of manually creating list of all weeks of the year and adding it in one go, but likely would be a limit?

Last, but not least, I'm only interested on current week and last week scores, anything older I'd like to keep it to have some historical data but I don't query it in the game, so could potentially get rid of indexes of older weeks.

Cheers!

like image 284
Javier C. H. Avatar asked Feb 20 '18 14:02

Javier C. H.


1 Answers

Thanks to @Tristan for pointing me in the right direction.

I used the following code to define the index and now warning is gone:

"game_scores-weekly": {
  "$date": {
    ".indexOn": ["score", "uid"]
  }
} 

Seems super obvious now but couldn't find anything clear in the documentation.

Note that $date could be any name really, seems like you can specify a variable value using any $identifier.

like image 93
Javier C. H. Avatar answered Sep 22 '22 04:09

Javier C. H.