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
Thanks in advanced
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 indexes for any fields 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 broswer and you index will be created automatically.
So Firestore require an index so you can have very fast queries.
An index is simply a database inventory (a record of what is where) and each index is a specific inventory of a specific thing (a property and its value). If there wasn't an inventory, to perform a query where someProperty
is someValue
, the machine would have to iterate over the entire collection to determine which documents have that property and that value. By keeping an inventory of properties (a record of which properties and what values are in which documents), when you perform a query, the machine goes straight to the inventory before going to the collection. This only works because the inventory (the index) is always ordered by value—the index can never be out of order. Therefore, to fetch documents where the value is between x
and y
, the machine just has to find the first document in the inventory at x
and span to y
and pull those documents from the collection. The machine doesn't even have to iterate over the entire inventory. This is partly why Firestore queries are so fast and why the size of the collection has no impact on the performance of the query and why you only need to index properties that need to be queried.
来源:https://stackoverflow.com/questions/53790175/why-does-this-firestore-query-require-an-index