Search code examples
javascriptfirebasegoogle-cloud-firestoreangularfire2

Why does this firestore query require an index?


I have a query with a where() method with an equality operator and then an orderBy() method and I can't figure out why it requires an index. The where method checks for a value in an object (a map) and the order by is with a number.

The documentation says

If you have a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field

So I would have thought that an equality filter would be fine.

Here is my query code:

this.afs.collection('posts').ref
.where('tags.' + this.courseID,'==',true)
.orderBy("votes")
.limit(5)
.get().then(snap => {
  snap.forEach(doc => {
    console.log(doc.data());
  });
});

Here is an example of the database structure enter image description here


Solution

  • Why does this Firestore query require an index?

    As you probably noticed, queries in Cloud Firestore are very fast and this is because Firestore automatically creates an index for any field you have in your document. So when you simply filter with a range comparison, Firestore creates the required index automatically. If you also try to order your results, another index is required. This kind of index is not created automatically. You should create it yourself. This can be done, by creating it manually in your Firebase Console or you'll find in your logs a message that sounds like this:

    FAILED_PRECONDITION: The query requires an index. You can create it here: ...
    

    You can simply click on that link or copy and paste the URL into a web browser and your index will be created automatically.

    So Firestore requires an index so you can have very fast queries.