Why does this firestore query require an index?

不羁岁月 提交于 2019-12-02 03:10:27

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!