Home > database >  How do I implement an index for where and orderBy timestamp?
How do I implement an index for where and orderBy timestamp?

Time:03-23

I have this field for the collection in users with either 2 status of condition1 and condition2. And I also wanted to order this in descending order. I tried it with this but it will display that I first need to create an index.

The status is in string. And the createdAt is in timestamp

 const userRef = collection(db, "users");
      const q = query(
        ordersRef,
        where("status", "==", "Condition1"),
        orderBy("createdAt", "desc")
      );
      const querySnapshot = await getDocs(q);

Also, is it necessary to filter this with Firebase or I could just filter using Javascript? However, I would still like to know how I can use indexing here.

CodePudding user response:

If you attempt the query above without first creating the required index, Cloud Firestore returns an error message containing a link you can follow to create the missing index.

This happens any time you attempt a query not supported by an index. You can also define and manage composite indexes which store a sorted mapping of all the documents in a collection, based on an ordered list of fields to index manually by using the console or by using the Firebase CLI.

Cloud Firestore does not automatically create composite indexes like it does for single-field indexes because of the large number of possible field combinations. Instead, Cloud Firestore helps you identify and create required composite indexes as you build your app. Follow the generated link to the Firebase console, review the automatically populated info, and click Create. Indexes can take a few minutes to build, depending on the size of the query.

After you create them, you can see your indexes and their status in the Composite Indexes section. If they're still building, the Firebase console includes a building status bar.

  • Related