fyllepo
fyllepo

Reputation: 2204

Firebase Firestore compound query variations

I have a dynamically constructed Firestore query, like so:

    let db = firebase.firestore().collection('vehData')

    if (this.filters.model.selected) {
      db = db.where('Model', '==', this.filters.model.selected)
    }

    if (this.filters.condition.selected) {
      db = db.where('TitleStatus', '==', this.filters.condition.selected)
    }

    if (this.filters.year.selected) {
      db = db.where('Year', '==', this.filters.year.selected)
    }

    if (this.filters.autopilot.selected) {
      db = db.where('Autopilot', '==', this.filters.autopilot.selected)
    }

    if (this.filters.battery.selected) {
      db = db.where('Battery', '==', this.filters.battery.selected)
    }

    if (this.filters.sortBy.selected) {
      db = db.orderBy(this.filters.sortBy.selected, this.filters.sortBy.ascOrDesc)
    }

    db.limit(200).get().then((querySnapshot) => { ... })

this.filters is just a data model for a group of select inputs.

The issue however, is that Firebase insists I have a composite index setup for every single variation of the above query, for example: Model ASC TitleStatus ASC OR Model ASC TitleStatus ASC Year ASC OR Model ASC TitleStatus ASC Year ASC Autopilot ASC

Making an index for every scenario / possible combination of filters would not be an option obviously, has anyone got any tips on how I may get around this limitation?

Upvotes: 0

Views: 370

Answers (2)

fyllepo
fyllepo

Reputation: 2204

I created a script to loop through all possible variations of my query via JavaScript, since indexes are represented as JSON, it was trivial to create a streamlined process once I had gotten the logic together to permutate my queries.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317477

There are no workarounds for creating necessary indexes in Firestore. The only way that Firestore can be massively scalable is to require every query to use an index.

If you don't care for the manual process of creating each index by clicking the link in the error message, you could construct a Firestore rules file to be deployed by the Firebase CLI. It would be possible to write some code to compute and populate the file automatically. Once that's done, you would no longer have to create indexes manually, preferring to use the CLI to deploy the rules once.

When you use the CLI to initialize a new project space, tell it you want to init Firestore, and it will generate a basic json file for you to modify and deploy. Typically you would check your Firebase CLI project files into source control.

Upvotes: 1

Related Questions