Demo, all content is generated
Question

Firestore query works in the emulator, fails in production with 'The query requires an index'

Solved · 951 views · asked by ellie_vc · edited

Tested everything against the local emulator, deployed, and the orders page is empty. Console shows:

FirebaseError: [code=failed-precondition]: The query requires an index. You can create it here: https://console.firebase.google.com/...

Query is where("shopId", "==", id), orderBy("createdAt", "desc"). Why would the emulator not complain?

What I’ve tried

Clicked the link, it made an index, but it says "Building" for 10 minutes. Also not sure how to not have this happen for every new query.

Comment
Click the link in the error, it prefills the exact index. wes_codes · edited

2 answers

Marked as helpful by the asker
sven_fire · edited

The emulator doesn't enforce composite indexes, so you only find out in production. Equality + orderBy on a different field always needs one.

The link is fine for a one-off, building usually takes a few minutes (longer for big collections). For the future, keep indexes in code:

firebase firestore:indexes > firestore.indexes.json

Commit that file, and it deploys with firebase deploy --only firestore:indexes. When you add a query, add the index there in the same change. You can also ask Windsurf to update firestore.indexes.json whenever it writes a new query, it's good at that once told.

Comment
index finished building and orders are back. exporting the file now ellie_vc · edited
mira_dev · edited

Two related gotchas once you start adding indexes: if you filter with an inequality (>, <, !=), the first orderBy generally has to be on that same field, otherwise the index link won't help. And each index costs a little on every write, so don't create one per experiment and forget it.

Comment
the inequality one would have been my next question, thanks ellie_vc · edited