Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 734
tokism Avatar asked Dec 15 '18 06:12

tokism


People also ask

How do I turn off indexing in firestore?

Remove indexesGo to the Cloud Firestore section of the Firebase console. Click the Indexes tab. Hover over the index you want to delete and select Delete from the context menu. Confirm that you want to delete it by clicking Delete from the alert.

What is index in cloud firestore?

A single-field index stores a sorted mapping of all the documents in a collection that contain a specific field. Each entry in a single-field index records a document's value for a specific field and the location of the document in the database. Cloud Firestore uses these indexes to perform many basic queries.

What are indexes in Firebase?

Defining Data Indexes Specifically, Firebase allows you to do ad-hoc queries on a collection of nodes using any common child key. As your app grows, the performance of this query degrades.

What file should be used for firestore indexes?

From the CLI, edit your index configuration file, with default filename firestore. indexes. json , and deploy using the firebase deploy command.


1 Answers

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.

like image 183
Alex Mamo Avatar answered Sep 18 '22 22:09

Alex Mamo