Kushagra Gour
Kushagra Gour

Reputation: 4966

Hitting maximum number of composite indexes in Firestore

I have a Firestore database in which I store a game's level score for various levels in a collection scores, like so:

player1: { levels: {
 1: { score: 2343, timestamp: t1 },
 2: { score: 434, timestamp: t2 },
},
player2: { levels: {
 1: { score: 23, timestamp: t3 },
 2: { score: 34, timestamp: t4 },
}

To get the top scores of any level X, I run the query:

collection('scores')
 .orderBy('levels.X.score')
 .orderBy('levels.X.timestamp', 'desc')

This requires to create a composite index for each level: collection:score, levels.x.score asc, levels.x.timestamp desc

A limit of 200 composite indexes means I'll only be able to create 200 levels in my database. Is there a way we can increases the limit, may be at some cost? Or is there a way I can modify my database structure/query to prevent this limit from reaching?

Upvotes: 2

Views: 1521

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

Firestore limits can't be changed.

You will have to change the way your data is modeled. Consider storing each score as a separate document in a collection that you can query. So you would have:

/scores             // collection for all scores
  /some-id          // random id for this document with scores
    - playerId
    - level
    - score
    - timestamp

Then you can query across all the scores for a given level

firestore
    .collection('scores')
    .where('level', '==', X)
    .orderBy('score')
    .orderBy('timestamp')

Or something along those lines. You will need just one composite index to support this query.

Upvotes: 4

Related Questions