Skip to main content
Published in Engineering Insights

An Introduction to Firebase's Cloud Firestore: Part II

An Introduction to Firebase's Cloud Firestore: Part II
Table of contents
  1. ‍TL;DR
  2. Background
  3. Querying
  4. Limitations
  5. Since July 29, 2024, Firestore Supports Range Filters on Multiple Fields
  6. How to Order Fields When a Query Filters on Several Ranges
  7. Automatic and Manual Indexes in Firestore
  8. How to Create a Missing Firestore Index
  9. Index Exemptions and Index Merging
  10. Firestore Index and Query Limits
  11. Recap

‍TL;DR#

  • Firestore's indexing rules aim to protect you from slow queries.
  • These indexing rules sometimes require you to either filter data yourself or to restructure your database.

Background#

If you missed Part I, you can find it here.
We won't be continuing the same project from Part I, but this post does assume knowledge of the topics covered in Part I, such as the different fundamental data types (like Snapshots and References).

Querying#

Firestore's Query API will be largely familiar to anyone with a background in relational databases, as it provides a SQL-like syntax for filtering and sorting data.
However, Firestore has a much more restricted set of tools compared to a relational database system like Postgres or MySQL.
Firestore keeps things to the bare minimum, which requires you to think ahead when structuring and querying your data.Firestore exposes a Query API with some methods that might look pretty familiar.
For example, the following query returns all users who are 30 years old:

JavaScript
const users = database.collection('users').where('age', '==', 30)

Query methods return a Query object, so you can chain together multiple methods to create more complex queries.

JavaScript
const users = database
  .collection('users')
  .where('age', '>', 18)
  .where('age', '<', 45)

Firestore also supports several other SQL-like methods.

JavaScript
const users = database
  .collection('users')
  .where('age', '>', 18)
  .select('name', 'birthday')
  .limit(10)

A list of all available methods can be found in the reference documentation.
Some methods that are particularly interesting are stream, which lets you stream snapshots as they are retrieved, and the startAt and startAfter methods, which allow you to paginate your data.

Much like a Reference, calling get on a Query object executes the query and returns a Snapshot, which you can then manipulate as usual.

JavaScript
const userQuery = database.collection('users').where('age', '<=', 25)
const userSnapshots = await userQuery.get()
userSnapshots.forEach(snapshot => console.log(snapshot.data()))

Firestore's API is intentionally compact, so it requires a bit of planning ahead of time to make sure that your database structure allows for quick queries.
Many data organization strategies from relational databases, such as using highly normalized tables with a lot of references, won't work well in Firestore, and the API reflects that.

Limitations#

Once you start filtering by multiple fields, you might run into some errors.
But don't worry, Firestore will point you in the right direction!

JavaScript
const users = database
  .collection('users')
  .where('age', '>', 30)
  .where('name', '==', 'SomeName')
// => Error: The query requires an index. You can create it here: <:long-url:>

In Part I of this series, I mentioned that Firestore uses indexes for everything.
By default, Firestore creates indexes for every subfield in all of your documents, but it doesn't create indexes for multiple subfields.
You'll have to do that yourself, but if you follow the link in the error message, Firestore will walk you through the whole process.Sometimes, however, Firestore is not nearly as helpful.
For example, take a look at this query:

JavaScript
const users = database
  .collection('users')
  .where('age', '>', 30)
  .where('name', '>=', 'SomeName')
// => Error: Cannot have inequality filters on multiple properties

Cannot have inequality filters on multiple properties

We get an error, but what do we do about it?

Again, this is because of Firestore's index rules.
Firestore enforces rules to keep queries fast, which it accomplishes by only allowing queries where records will be adjacent to each other within a given index.
However, this query doesn't guarantee that the records are adjacent, meaning that Firestore would have to scan the entire index.In instances like this, Firestore doesn't have an easy fix, and its error message, while somewhat confusing, reflects that.
Getting around this constraint is a bit trickier.
Unlike our earlier query, we can't simply create a new index for this particular query.One option is to use only one of the where filters and do the other filter in your application, although this can quickly slow down your application on large projects since you may be loading a lot of data into memory.
If filtering in your application is problematic, you may need to reorganize your database structure to allow for more efficient queries.

Since July 29, 2024, Firestore Supports Range Filters on Multiple Fields#

Firestore now allows range and inequality filters on more than one field in a single query. Google's release notes list the feature in Preview on March 27, 2024, and as generally available on July 29, 2024. The post's summary says "Firestore's indexing rules aim to protect you from slow queries." This post's multiple-inequality example and its error describe the rule before that change.

The July 29, 2024 note says, "You can now apply range and inequality filters to multiple fields in a query." The Firebase docs page on multiple range fields says, "Cloud Firestore supports using range and inequality filters on multiple fields in a single query." Both pages were read on November 15, 2026.

The same docs pages set these rules for such a query.

RuleWhat Google's docs say today
Number of fields"Cloud Firestore limits the number of range or inequality fields to 10."
Not supported"Queries with range or inequality filters on document fields and only equality constraints on the document key (__name__) aren't supported."
Billing"Queries with range and inequality filters on multiple fields are billed based on documents read and index entries read."
Missing fieldsIn the queries page list of Standard edition limits: "A query with an inequality filter on a field implies ordering by that field and filters for existence of that field."

How to Order Fields When a Query Filters on Several Ranges#

Order index fields with equalities first, then the "most selective range or inequality field." In the orderBy clause, list the range fields "in decreasing order of query constraint selectivity." The post says Firestore "requires a bit of planning ahead of time to make sure that your database structure allows for quick queries."

Google's docs page on multiple range fields gives this guidance.

  1. Equality fields first. The docs title this rule "Order index fields by equalities followed by most selective range or inequality field."
  2. Rank the range fields by selectivity. The docs say, "Higher selectivity matches a smaller subset of documents."
  3. Write the orderBy calls in that order. The docs tell you to specify an orderBy clause "that orders fields in decreasing order of query constraint selectivity."

In Google's example, the salary filter matches fewer employees than the experience filter, so salary goes first. Here is the query from the docs.

JavaScript
db.collection("employees")
  .where("salary", ">", 100000)
  .where("experience", ">", 0)
  .orderBy("salary")
  .orderBy("experience");

The docs say an "ORDER BY a ASC, b ASC query requires a composite index on the a ASC, b ASC fields." So this query runs on an index of salary, then experience. Google's optimize page compares the two index orders for the same filters.

IndexIndex entries scannedDocuments returned
experience ASC, salary ASC950005
salary ASC, experience ASC10005

These are Google's example figures for its employees collection.

Automatic and Manual Indexes in Firestore#

Firestore has two kinds of index: automatic indexes and manual indexes. Google's docs say they were "previously known as single-field and composite indexes, respectively." The post says "By default, Firestore creates indexes for every subfield in all of your documents, but it doesn't create indexes for multiple subfields."

The defaults have exceptions. In the index types docs, "Automatic indexes with collection group scope are not maintained by default." An indexing exemption can also turn an automatic index off for a field, or turn on one the automatic settings disabled. The page was read on November 15, 2026.

An automatic index covers one field. A manual index lists documents in the order of several fields you choose. Firestore "doesn't automatically create indexes for combinations of fields because of the large number of possible field combinations." A manual index can hold at most one array field. Part I's Document Indexes section covers indexes on map subfields.

Each indexed field gets an index mode. The mode decides which query clauses the index supports.

Index modeWhat the docs say it supports
AscendingThe clauses <, <=, ==, >=, >, !=, in and not-in, plus sorting in ascending order
DescendingThe same clauses, plus sorting in descending order
Array-containsThe array-contains and array-contains-any clauses
VectorThe FindNearest clause
Field typeAutomatic indexes by default
Not an array or a mapTwo collection scope indexes, one ascending and one descending
MapAn ascending and a descending index for each subfield that is not an array or a map, one of each for the whole map value, and an array-contains index for each array subfield
ArrayAn ascending and a descending index for the whole array value, plus one array-contains index

A document appears in an index only if it has a value for each field the index uses. Without one, the docs say the document "will never be returned as a result for any query based on the index."

How to Create a Missing Firestore Index#

You can create a missing index three ways: follow the error link, use the Firebase console, or deploy it with the Firebase CLI. The post says "if you follow the link in the error message, Firestore will walk you through the whole process." All three are in Google's manage indexes docs, which were read on November 15, 2026.

The docs say a compound query with a range clause that has no matching index returns an error. That error "includes a direct link to create the missing index in the Firebase console."

  1. Follow the error link. Google says to "review the automatically populated info, and click Create."
  2. Use the Firebase console. In the Indexes tab, "click Add Index." Then enter the collection name, set the fields to order by and click Create.
  3. Use the Firebase CLI. Run firebase init firestore in your project directory. The CLI generates a JSON file with default indexes. Edit it and deploy it with firebase deploy.

To deploy "indexes and rules only," add --only firestore to the deploy command.

For a field that is not an array or a map, you must pick ascending or descending order, "even if you don't need the field for ordering." And before you create an index, the docs say to hold one of these roles: roles/datastore.owner, roles/datastore.indexAdmin, roles/editor or roles/owner. For custom roles, the docs say to "assign all of the following permissions to create indexes": datastore.indexes.create, datastore.indexes.delete, datastore.indexes.get, datastore.indexes.list and datastore.indexes.update.

Index Exemptions and Index Merging#

An exemption can turn an automatic index off for a field, or turn on one the automatic settings disabled. Merging lets one set of indexes serve several queries that use equality filters. The post says Firestore "requires you to think ahead when structuring and querying your data."

In the index types docs, "Reducing the number of indexed fields reduces storage costs and can improve write performance." The docs name four cases where an exemption can help. A field with an exemption "can still be indexed as part of a manual index."

CaseWhat the docs say
Large string fieldsIf you do not query a long string field, "you can cut storage costs by exempting the field from indexing."
Sequential valuesFor an indexed field that rises or falls in sequence, like a timestamp, "the maximum write rate to the collection is 500 writes per second."
TTL fields"Indexing on TTL fields is enabled by default and can affect performance at higher traffic rates."
Large array or map fieldsThey "can approach the limit of 40,000 index entries per document."

Merging works on equality filters. The docs say, "For queries with multiple equality (==) clauses and, optionally, an orderBy clause, Cloud Firestore can re-use existing indexes."

Google's example is a restaurants collection. Its queries combine equality filters on category, city and editors_pick with a sort on star_rating. One index per query means four indexes. With merging, three indexes cover them:

  • category, star_rating
  • city, star_rating
  • editors_pick, star_rating

The docs add that the smaller set "also supports an additional query." For an array-contains query with extra clauses, Google recommends a manual index to avoid "performance loss caused by index merging."

Firestore Index and Query Limits#

Firestore sets limits on both its indexes and the queries you run. Google's quotas page lists 200 composite indexes per database without billing and 1000 with billing enabled. For the 1000 limit, it says you can contact support to request an increase. A query can have at most 10 range or inequality fields. The post says "Firestore is a great tool because it aims to be scalable by default." The quotas page was read on November 15, 2026.

Index limitValue
Composite indexes per database200 without billing, 1000 with billing
Index entries per document40,000, counting single-field and composite entries
Fields in a composite index100
Size of one index entry7.5 KiB
Sum of a document's index entry sizes8 MiB
Size of an indexed field value1500 bytes

The quotas page adds, "Field values over 1500 bytes are truncated. Queries involving truncated field values may return inconsistent results."

Queries have limits too. The queries page lists the first three rows below as Standard edition limits. The last row comes from the multiple range fields page.

Query limitValue
or, in and array-contains-any30 disjunctions in disjunctive normal form, a fixed limit
not-inUp to 10 comparison values
Filters, sort orders and parent pathTheir sum cannot exceed 100. Google counts it on the query's disjunctive normal form. The parent path counts 1 for a subcollection and 0 for a root collection.
Range or inequality fields10

Recap#

Firestore is a great tool because it aims to be scalable by default.
By making restrictions to limit slow queries, Firestore enforces index usage for all queries, and while this does require some extra planning on the developer's part, these limitations exist to help us in the long run.

Frequently asked questions

How do I execute a Query object?

Call get to execute it and receive a Snapshot. The example then reads each document with data().

What should I do when a query requires an index?

Follow the link in the error message. Firestore walks you through creating the missing index for multiple subfields.

Why does the multiple-inequality example fail?

The query does not guarantee adjacent records in an index, so it would require scanning the entire index. The described rules reject it to keep queries fast.

What is the drawback of filtering in the application?

It may load a lot of data into memory and slow down a large application. If that is a problem, the database structure may need to change.

Does Firestore support range filters on more than one field?

Yes. Google's release notes list range and inequality filters on multiple fields in a single query as generally available on July 29, 2024. The docs limit a query to 10 range or inequality fields and bill it on documents read and index entries read. This post's multiple-inequality example and its error describe the rule before that change.

How do I order the fields in a query with several range filters?

Order index fields with equality fields first, then the most selective range field. In orderBy, list the range fields from most to least selective. In Google's employees example, putting salary before experience scans 1000 index entries instead of 95000 for the same five documents.

How do I create a missing Firestore index?

Follow the link in the error message and click Create. For a vector index, the docs say "the error message will include a Google Cloud CLI command to create the missing vector index." You can also open the Indexes tab in the Firebase console and click Add Index, or define indexes in a file with the Firebase CLI and run firebase deploy.

How many indexes can a Firestore database have?

Google's quotas page lists 200 composite indexes per database when billing is not enabled and 1000 when billing is enabled. A document can have a maximum of 40,000 index entries, counting single-field and composite entries together.

Stay In The Loop

Never miss an update. Get the latest blogs, webinars, and expert insights straight to your inbox from The Gnar.