Fetching Data with Firestore Structured Queries and Index Creation

Overview

This article explains how to fetch data from Firestore using the structured query format via REST API, demonstrates a sample query code, and covers the essential step of creating Firestore indexes to support complex queries.

Fetching Data Using Firestore Structured Query

In Firestore’s REST API, you can fetch data by sending a POST request with a JSON payload that specifies the structured query. The structure includes collection references, filtering conditions, and ordering of results.

Here is a sample query payload example which fetches documents from the collection group edited_purchase_order where the approved field is true, and orders the results by the submitted_date field in ascending order:

const payload = {
    "structuredQuery": {
        "from": [
            { "collectionId": "edited_purchase_order", "allDescendants": true }
        ],
        "where": {
            "fieldFilter": {
                "field": { "fieldPath": "approved" },
                "op": "EQUAL",
                "value": { "booleanValue": true }
            }
        },
        "orderBy": [
            {
                "field": { "fieldPath": "submitted_date" },
                "direction": "ASCENDING"
            }
        ]
    }
};

const headers = { 'Content-Type': 'application/json' };

const response = https.post({
    url: FIRESTORE_URL,
    headers: headers,
    body: JSON.stringify(payload)
});

This sends the query to Firestore and returns matching documents.firebase.google+1

Why Firestore Indexes Are Needed

Firestore requires indexes to efficiently execute queries involving multiple filters, range filters, or order by clauses. Basic single-field indexes are created automatically, but if you combine filters and ordering on multiple fields or collections, you need to create a composite index.

If an index is missing, Firestore returns an error with a direct link to create the index in the Firebase console.

Creating Firestore Indexes

Manual Index Creation via Firebase Console

  1. Navigate to the Cloud Firestore section of your Firebase project.
  2. Go to the Indexes tab.
  3. Click Add Index.
  4. Fill in:
  • Collection ID (e.g., edited_purchase_order)
  • Fields to filter/order by (approved field, submitted_date field)
  1. Specify sort order for each field (e.g., approved ascending or equal operator, submitted_date ascending).
  2. Click Create.

It may take a few minutes for Firestore to build the index. After building, the queries using that index will work properly.firebase.google+1

Using Firebase CLI for Index Management

You can manage indexes using a firestore.indexes.json file in your project and deploy them via the Firebase CLI:

Example for edited_purchase_order collection composite index:

json
{
  "indexes": [
    {
      "collectionGroup": "edited_purchase_order",
      "queryScope": "COLLECTION",
      "fields": [
        { "fieldPath": "approved", "order": "ASCENDING" },
        { "fieldPath": "submitted_date", "order": "ASCENDING" }
      ]
    }
  ]
}

Run:

text
firebase deploy --only firestore:indexes

This automates index creation in a version-controlled manner.stackoverflow+1

Best Practices and Notes

  • Always check Firestore error messages for direct links to create missing indexes.
  • Use descriptive names and consistent ordering in indexes for queries that combine filters and sorting.
  • Index build time depends on collection size.
  • Ensure the user or service account has appropriate permissions to create indexes (roles/datastore.owner or roles/datastore.indexAdmin).cloud.google+1

Leave a comment

Your email address will not be published. Required fields are marked *