Bird
Raised Fist0
GCPcloud~5 mins

Firestore queries and indexes in GCP - Commands & Configuration

Choose your learning style10 modes available
Introduction
Firestore stores data in documents and collections. To find data quickly, Firestore uses queries. Some queries need indexes to work fast and correctly.
When you want to find documents with specific field values in a collection.
When you need to sort query results by one or more fields.
When you want to filter documents using multiple conditions on different fields.
When you want to paginate query results for a better user experience.
When Firestore tells you an index is missing for your query.
Config File - firestore.indexes.json
firestore.indexes.json
{
  "indexes": [
    {
      "collectionGroup": "my-collection",
      "queryScope": "COLLECTION",
      "fields": [
        { "fieldPath": "status", "order": "ASCENDING" },
        { "fieldPath": "createdAt", "order": "DESCENDING" }
      ]
    }
  ],
  "fieldOverrides": []
}

This file defines a composite index for the collection named my-collection. It indexes the status field in ascending order and the createdAt field in descending order. Firestore uses this index to speed up queries that filter or sort by these fields.

Commands
This command creates a composite index for the collection group 'my-collection' on the fields 'status' ascending and 'createdAt' descending. It enables Firestore to run queries filtering or sorting by these fields efficiently.
Terminal
gcloud firestore indexes create --collection-group=my-collection --field-config=fieldPath=status,order=ASCENDING --field-config=fieldPath=createdAt,order=DESCENDING
Expected OutputExpected
Creating index... This may take a few minutes. Index created successfully.
→
--collection-group - Specifies the collection group to index.
→
--field-config - Defines each field and its sort order in the index.
Lists all Firestore indexes in your project so you can verify the new index exists.
Terminal
gcloud firestore indexes list
Expected OutputExpected
NAME: projects/my-project/databases/(default)/collectionGroups/my-collection/indexes/abcd1234 STATE: READY FIELDS: - status (ASCENDING) - createdAt (DESCENDING)
Deletes the Firestore index with ID 'abcd1234' if you no longer need it to save resources.
Terminal
gcloud firestore indexes delete abcd1234
Expected OutputExpected
Deleting index abcd1234... Index deleted successfully.
Key Concept

If you remember nothing else from this pattern, remember: Firestore needs indexes to run complex queries fast and you must create those indexes before running such queries.

Common Mistakes
Running a query that filters or sorts on multiple fields without creating the required composite index.
Firestore will reject the query and show an error asking for an index, causing your app to fail or hang.
Create the composite index using the gcloud command or Firestore console before running the query.
Creating an index with incorrect field order or missing fields.
The index won't match the query requirements, so Firestore will still reject the query.
Match the index fields and their order exactly to the query's filter and sort fields.
Summary
Create composite indexes to support Firestore queries with multiple filters or sorting.
Use the gcloud CLI to create, list, and delete Firestore indexes.
Always verify your indexes exist and match your query patterns to avoid query errors.

Practice

(1/5)
1. What is the main purpose of indexes in Firestore queries?
easy
A. To make queries faster and more efficient
B. To store large files like images
C. To backup data automatically
D. To encrypt data for security

Solution

  1. Step 1: Understand what indexes do in Firestore

    Indexes help Firestore find data quickly without scanning all documents.
  2. Step 2: Relate indexes to query performance

    By using indexes, queries run faster and use less resources.
  3. Final Answer:

    To make queries faster and more efficient -> Option A
  4. Quick Check:

    Indexes speed up queries = D [OK]
Hint: Indexes speed up data search in Firestore queries [OK]
Common Mistakes:
  • Thinking indexes store files
  • Confusing indexes with backups
  • Assuming indexes encrypt data
2. Which of the following is the correct syntax to create a simple Firestore query filtering by a field age equal to 30?
easy
A. db.collection('users').filter('age', '=', 30)
B. db.collection('users').where('age', '==', 30)
C. db.collection('users').query('age' == 30)
D. db.collection('users').find('age', 30)

Solution

  1. Step 1: Recall Firestore query syntax

    Firestore uses where(field, operator, value) to filter data.
  2. Step 2: Match syntax with options

    db.collection('users').where('age', '==', 30) uses where('age', '==', 30), which is correct syntax.
  3. Final Answer:

    db.collection('users').where('age', '==', 30) -> Option B
  4. Quick Check:

    Correct Firestore filter syntax = B [OK]
Hint: Use .where(field, '==', value) for filtering in Firestore [OK]
Common Mistakes:
  • Using .filter instead of .where
  • Using == inside query string
  • Using .find which is not Firestore syntax
3. Given this Firestore query:
db.collection('orders').where('status', '==', 'shipped').orderBy('date', 'desc')

What must you do to avoid an error when running this query?
medium
A. Remove the orderBy clause
B. Create a single-field index on date only
C. No index needed, Firestore handles it automatically
D. Create a composite index on status and date

Solution

  1. Step 1: Understand query with multiple filters and sorting

    This query filters by status and sorts by date.
  2. Step 2: Know Firestore index requirements

    Firestore requires a composite index for queries with multiple filters or sorting on different fields.
  3. Final Answer:

    Create a composite index on status and date -> Option D
  4. Quick Check:

    Composite index needed for multiple filters + orderBy = A [OK]
Hint: Use composite indexes for queries with filters and sorting [OK]
Common Mistakes:
  • Assuming single-field index is enough
  • Thinking Firestore auto-creates all indexes
  • Removing orderBy to fix error
4. You wrote this Firestore query:
db.collection('products').where('price', '>', 100).orderBy('name')

But it gives an error about missing index. What is the best fix?
medium
A. Change price filter to ==
B. Remove the orderBy clause
C. Create a composite index on price (ascending) and name (ascending)
D. Create a single-field index on name only

Solution

  1. Step 1: Identify query components causing index error

    The query filters by price > 100 and orders by name.
  2. Step 2: Understand Firestore index needs for range filter + orderBy

    Firestore requires a composite index on both fields with correct sort order.
  3. Final Answer:

    Create a composite index on price (ascending) and name (ascending) -> Option C
  4. Quick Check:

    Composite index needed for range filter + orderBy = C [OK]
Hint: Create composite index matching filter and orderBy fields [OK]
Common Mistakes:
  • Removing orderBy instead of indexing
  • Changing filter operator incorrectly
  • Creating only single-field index
5. You want to query a Firestore collection events to find documents where type is 'conference' and attendees is greater than 100, sorted by date ascending. Which index should you create to support this query?
hard
A. Composite index on type (ascending), attendees (ascending), and date (ascending)
B. Single-field index on date only
C. Composite index on type (descending) and date (ascending)
D. No index needed, Firestore supports this query by default

Solution

  1. Step 1: Analyze query filters and sorting

    The query filters by type == 'conference' and attendees > 100, and sorts by date ascending.
  2. Step 2: Determine required index type

    Multiple filters plus sorting require a composite index including all these fields with correct order.
  3. Final Answer:

    Composite index on type (ascending), attendees (ascending), and date (ascending) -> Option A
  4. Quick Check:

    Composite index covers all filters and orderBy fields = A [OK]
Hint: Include all filter and orderBy fields in composite index [OK]
Common Mistakes:
  • Creating only single-field index
  • Using wrong sort order in index
  • Assuming no index needed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard