Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase firestore query: "Error: 9 FAILED_PRECONDITION: The query requires an index. You can create it here"

I have what I thought was a simple query on a collection called 'email':

 const emailQuery = admin
    .firestore()
    .collection('email')
    .where('sendAt', '>=', new Date())
    .where('orderId', '==', doc.orderId)
    .where('brandId', '==', doc.brandId);

I'm receiving the error in the subject of this post, indicating that I need to create an index for this query. I've tried creating a couple for the relevant fields, but I'm unsure of why it's needed since only one field is ordered--and the error remains despite these indexes:

sendAt -> Ascending, brandId -> Ascending, orderId -> Ascending

sendAt -> Descending, brandId -> Ascending, orderId -> Ascending

I'm not specifying an orderBy as you can see. Also, sendAt is a date, while the other two are simple strings that don't need to be ordered.

What kind index do I need, or how do I get past this error?

Thanks!

like image 816
Dygerati Avatar asked Jul 06 '18 19:07

Dygerati


1 Answers

From the documentation:

If you attempt a compound query with a range clause that doesn't map to an existing index, you receive an error. The error message includes a direct link to create the missing index in the Firebase console.

To state it another way: when you use a comparison that involves < or >, there is an implicit ordering in the query on that field. When used in combination with conditions on other fields, an index is required for the particular collection ID.

The error message that you started to quote in the title of your question should contain a link to the console that will create the required index for that query. Just follow that link and authorize the creation of the index.

like image 125
Doug Stevenson Avatar answered Sep 22 '22 15:09

Doug Stevenson