FirebaseFirestore

public classFirebaseFirestore


Represents a Cloud Firestore database and is the entry point for all Cloud Firestore operations.

Subclassing Note: Cloud Firestore classes are not meant to be subclassed except for use in test mocks. Subclassing is not supported in production code and new SDK releases may break code that does so.

Summary

Public methods

@NonNullListenerRegistration

Attaches a listener for a snapshots-in-sync event.

@NonNullListenerRegistration
addSnapshotsInSyncListener(
    @NonNullActivity activity,
    @NonNullRunnable runnable
)

Attaches a listener for a snapshots-in-sync event.

@NonNullListenerRegistration
addSnapshotsInSyncListener(
    @NonNullExecutor executor,
    @NonNullRunnable runnable
)

Attaches a listener for a snapshots-in-sync event.

@NonNullWriteBatch

Creates a write batch, used for performing multiple writes as a single atomic operation.

@NonNullTask<Void>

Clears the persistent storage, including pending writes and cached documents.

@NonNullCollectionReference
collection(@NonNullString collectionPath)

Gets aCollectionReference instance that refers to the collection at the specified path within the database.

@NonNullQuery

Creates and returns a newQuery that includes all documents in the database that are contained in a collection or subcollection with the givencollectionId.

@NonNullTask<Void>

Disables network access for this instance.

@NonNullDocumentReference
document(@NonNullString documentPath)

Gets a `DocumentReference` instance that refers to the document at the specified path within the database.

@NonNullTask<Void>

Re-enables network usage for this instance after a prior call todisableNetwork.

@NonNullFirebaseApp

Returns the FirebaseApp instance to which thisFirebaseFirestore belongs.

@NonNullFirebaseFirestoreSettings

Returns the settings used by thisFirebaseFirestore object.

static @NonNullFirebaseFirestore

Returns the defaultFirebaseFirestore instance for the defaultFirebaseApp.

static @NonNullFirebaseFirestore

Returns the defaultFirebaseFirestore instance for the providedFirebaseApp.

static @NonNullFirebaseFirestore

Returns theFirebaseFirestore instance for the defaultFirebaseApp.

static @NonNullFirebaseFirestore

Returns theFirebaseFirestore instance for the providedFirebaseApp.

@NonNullTask<Query>

Reads a FirestoreQuery from local cache, identified by the given name.

@NullablePersistentCacheIndexManager

Gets thePersistentCacheIndexManager instance used by thisFirebaseFirestore object.

@NonNullLoadBundleTask
loadBundle(@NonNull byte[] bundleData)

Loads a Firestore bundle into the local cache.

@NonNullLoadBundleTask

Loads a Firestore bundle into the local cache.

@NonNullLoadBundleTask

Loads a Firestore bundle into the local cache.

@NonNullTask<Void>

Executes a batchFunction on a newly createdWriteBatch and then commits all of the writes made by the batchFunction as a single atomic unit.

@NonNullTask<TResult>
<TResult>runTransaction(
    @NonNullTransaction.Function<TResult> updateFunction
)

Executes the givenupdateFunction and then attempts to commit the changes applied within the transaction.

@NonNullTask<TResult>
<TResult>runTransaction(
    @NonNullTransactionOptions options,
    @NonNullTransaction.Function<TResult> updateFunction
)

Executes the givenupdateFunction and then attempts to commit the changes applied within the transaction.

void

Sets any custom settings used to configure thisFirebaseFirestore object.

@NonNullTask<Void>

This method is deprecated.

Instead of creating cache indexes manually, consider usingenableIndexAutoCreation to let the SDK decide whether to create cache indexes for queries running locally.

static void
setLoggingEnabled(boolean loggingEnabled)

Globally enables / disables Cloud Firestore logging for the SDK.

@NonNullTask<Void>

Terminates thisFirebaseFirestore instance.

void
useEmulator(@NonNullString host, int port)

Modifies this FirebaseDatabase instance to communicate with the Cloud Firestore emulator.

@NonNullTask<Void>

Waits until all currently pending writes for the active user have been acknowledged by the backend.

Public fields

Public methods

addSnapshotsInSyncListener

public @NonNullListenerRegistration addSnapshotsInSyncListener(@NonNullRunnable runnable)

Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event indicates that all listeners affected by a given change have fired, even if a single server-generated change affects multiple listeners.

NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, but does not relate to whether those snapshots are in sync with the server. Use SnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or the server.

Parameters
@NonNullRunnable runnable

A callback to be called every time all snapshot listeners are in sync with each other.

Returns
@NonNullListenerRegistration

A registration object that can be used to remove the listener.

addSnapshotsInSyncListener

public @NonNullListenerRegistration addSnapshotsInSyncListener(
    @NonNullActivity activity,
    @NonNullRunnable runnable
)

Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event indicates that all listeners affected by a given change have fired, even if a single server-generated change affects multiple listeners.

NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, but does not relate to whether those snapshots are in sync with the server. Use SnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or the server.

Parameters
@NonNullActivity activity

The activity to scope the listener to.

@NonNullRunnable runnable

A callback to be called every time all snapshot listeners are in sync with each other.

Returns
@NonNullListenerRegistration

A registration object that can be used to remove the listener.

addSnapshotsInSyncListener

public @NonNullListenerRegistration addSnapshotsInSyncListener(
    @NonNullExecutor executor,
    @NonNullRunnable runnable
)

Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event indicates that all listeners affected by a given change have fired, even if a single server-generated change affects multiple listeners.

NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, but does not relate to whether those snapshots are in sync with the server. Use SnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or the server.

Parameters
@NonNullExecutor executor

The executor to use to call the listener.

@NonNullRunnable runnable

A callback to be called every time all snapshot listeners are in sync with each other.

Returns
@NonNullListenerRegistration

A registration object that can be used to remove the listener.

batch

public @NonNullWriteBatch batch()

Creates a write batch, used for performing multiple writes as a single atomic operation.

The maximum number of writes allowed in a single batch is 500, but note that each usage ofserverTimestamp,arrayUnion,arrayRemove, orincrement inside a transaction counts as an additional write.

Returns
@NonNullWriteBatch

The created WriteBatch object.

clearPersistence

public @NonNullTask<VoidclearPersistence()

Clears the persistent storage, including pending writes and cached documents.

Must be called while theFirebaseFirestore instance is not started (after the app is shutdown or when the app is first initialized). On startup, this method must be called before other methods (other thansetFirestoreSettings). If theFirebaseFirestore instance is still running, theTask will fail with an error code ofFAILED_PRECONDITION.

Note:clearPersistence() is primarily intended to help write reliable tests that use Cloud Firestore. It uses an efficient mechanism for dropping existing data but does not attempt to securely overwrite or otherwise make cached data unrecoverable. For applications that are sensitive to the disclosure of cached data in between user sessions, we strongly recommend not enabling persistence at all.

Returns
@NonNullTask<Void>

ATask that is resolved when the persistent storage is cleared. Otherwise, theTask is rejected with an error.

collection

public @NonNullCollectionReference collection(@NonNullString collectionPath)

Gets aCollectionReference instance that refers to the collection at the specified path within the database.

Parameters
@NonNullString collectionPath

A slash-separated path to a collection.

Returns
@NonNullCollectionReference

TheCollectionReference instance.

collectionGroup

public @NonNullQuery collectionGroup(@NonNullString collectionId)

Creates and returns a newQuery that includes all documents in the database that are contained in a collection or subcollection with the givencollectionId.

Parameters
@NonNullString collectionId

Identifies the collections to query over. Every collection or subcollection with this ID as the last segment of its path will be included. Cannot contain a slash.

Returns
@NonNullQuery

The created Query.

disableNetwork

public @NonNullTask<VoiddisableNetwork()

Disables network access for this instance. While the network is disabled, any snapshot listeners orget() calls will return results from cache, and any write operations will be queued until network usage is re-enabled via a call toenableNetwork.

Returns
@NonNullTask<Void>

A Task that will be completed once networking is disabled.

document

public @NonNullDocumentReference document(@NonNullString documentPath)

Gets a `DocumentReference` instance that refers to the document at the specified path within the database.

Parameters
@NonNullString documentPath

A slash-separated path to a document.

Returns
@NonNullDocumentReference

The DocumentReference instance.

enableNetwork

public @NonNullTask<VoidenableNetwork()

Re-enables network usage for this instance after a prior call todisableNetwork.

Returns
@NonNullTask<Void>

A Task that will be completed once networking is enabled.

getApp

public @NonNullFirebaseApp getApp()

Returns the FirebaseApp instance to which thisFirebaseFirestore belongs.

getFirestoreSettings

public @NonNullFirebaseFirestoreSettings getFirestoreSettings()

Returns the settings used by thisFirebaseFirestore object.

getInstance

public static @NonNullFirebaseFirestore getInstance()

Returns the defaultFirebaseFirestore instance for the defaultFirebaseApp.

Returns the same instance for all invocations. If no instance exists, initializes a new instance.

TheFirebaseFirestore instance.

getInstance

public static @NonNullFirebaseFirestore getInstance(@NonNullFirebaseApp app)

Returns the defaultFirebaseFirestore instance for the providedFirebaseApp.

For a givenFirebaseApp, invocation always returns the same instance. If no instance exists, initializes a new instance.

TheFirebaseFirestore instance.

Parameters
@NonNullFirebaseApp app

TheFirebaseApp instance that the returnedFirebaseFirestore instance is associated with.

getInstance

public static @NonNullFirebaseFirestore getInstance(@NonNullString database)

Returns theFirebaseFirestore instance for the defaultFirebaseApp.

Returns the same instance for all invocations given the same database parameter. If no instance exists, initializes a new instance.

TheFirebaseFirestore instance.

Parameters
@NonNullString database

The database ID.

getInstance

public static @NonNullFirebaseFirestore getInstance(@NonNullFirebaseApp app, @NonNullString database)

Returns theFirebaseFirestore instance for the providedFirebaseApp.

Returns the same instance for all invocations given the sameFirebaseApp and database parameter. If no instance exists, initializes a new instance.

TheFirebaseFirestore instance.

Parameters
@NonNullFirebaseApp app

TheFirebaseApp instance that the returnedFirebaseFirestore instance is associated with.

@NonNullString database

The database ID.

getNamedQuery

public @NonNullTask<QuerygetNamedQuery(@NonNullString name)

Reads a FirestoreQuery from local cache, identified by the given name.

The named queries are packaged into bundles on the server side (along with resulting documents) and loaded to local cache usingloadBundle. Once in local cache, you can use this method to extract a query by name.

getPersistentCacheIndexManager

public @NullablePersistentCacheIndexManager getPersistentCacheIndexManager()

Gets thePersistentCacheIndexManager instance used by thisFirebaseFirestore object.

This is not the same as Cloud Firestore Indexes. Persistent cache indexes are optional indexes that only exist within the SDK to assist in local query execution.

Returns
@NullablePersistentCacheIndexManager

ThePersistentCacheIndexManager instance or null if local persistent storage is not in use.

loadBundle

public @NonNullLoadBundleTask loadBundle(@NonNull byte[] bundleData)

Loads a Firestore bundle into the local cache.

Parameters
@NonNull byte[] bundleData

A byte array representing the bundle to be loaded.

Returns
@NonNullLoadBundleTask

ALoadBundleTask, which notifies callers with progress updates, and completion or error events.

loadBundle

public @NonNullLoadBundleTask loadBundle(@NonNullByteBuffer bundleData)

Loads a Firestore bundle into the local cache.

Parameters
@NonNullByteBuffer bundleData

A ByteBuffer representing the bundle to be loaded.

Returns
@NonNullLoadBundleTask

ALoadBundleTask, which notifies callers with progress updates, and completion or error events.

loadBundle

public @NonNullLoadBundleTask loadBundle(@NonNullInputStream bundleData)

Loads a Firestore bundle into the local cache.

Parameters
@NonNullInputStream bundleData

A stream representing the bundle to be loaded.

Returns
@NonNullLoadBundleTask

ALoadBundleTask, which notifies callers with progress updates, and completion or error events.

runBatch

public @NonNullTask<VoidrunBatch(@NonNullWriteBatch.Function batchFunction)

Executes a batchFunction on a newly createdWriteBatch and then commits all of the writes made by the batchFunction as a single atomic unit.

Parameters
@NonNullWriteBatch.Function batchFunction

The function to execute within the batch context.

Returns
@NonNullTask<Void>

A Task that will be resolved when the batch has been committed.

runTransaction

public @NonNullTask<TResult> <TResult>runTransaction(
    @NonNullTransaction.Function<TResult> updateFunction
)

Executes the givenupdateFunction and then attempts to commit the changes applied within the transaction. If any document read within the transaction has changed, the updateFunction will be retried. If it fails to commit after 5 attempts (the default failure limit), the transaction will fail. To have a different number of retries, use therunTransaction method instead.

Parameters
@NonNullTransaction.Function<TResult> updateFunction

The function to execute within the transaction context.

Returns
@NonNullTask<TResult>

The task returned from the updateFunction.

runTransaction

public @NonNullTask<TResult> <TResult>runTransaction(
    @NonNullTransactionOptions options,
    @NonNullTransaction.Function<TResult> updateFunction
)

Executes the givenupdateFunction and then attempts to commit the changes applied within the transaction. If any document read within the transaction has changed, the updateFunction will be retried. If it fails to commit after the maxmimum number of attempts specified in transactionOptions, the transaction will fail.

Parameters
@NonNullTransactionOptions options

The transaction options for controlling execution.

@NonNullTransaction.Function<TResult> updateFunction

The function to execute within the transaction context.

Returns
@NonNullTask<TResult>

The task returned from the updateFunction.

setFirestoreSettings

public void setFirestoreSettings(@NonNullFirebaseFirestoreSettings settings)

Sets any custom settings used to configure thisFirebaseFirestore object. This method can only be called before calling any other methods on this object.

setIndexConfiguration

@PreviewApi
public @NonNullTask<VoidsetIndexConfiguration(@NonNullString json)
This method is deprecated.

Instead of creating cache indexes manually, consider usingenableIndexAutoCreation to let the SDK decide whether to create cache indexes for queries running locally.

Configures indexing for local query execution. Any previous index configuration is overridden. The Task resolves once the index configuration has been persisted.

The index entries themselves are created asynchronously. You can continue to use queries that require indexing even if the indices are not yet available. Query execution will automatically start using the index once the index entries have been written.

The method accepts the JSON format exported by the Firebase CLI (`firebase firestore:indexes`). If the JSON format is invalid, this method throws an exception.

Parameters
@NonNullString json

The JSON format exported by the Firebase CLI.

Returns
@NonNullTask<Void>

A task that resolves once all indices are successfully configured.

Throws
java.lang.IllegalArgumentException java.lang.IllegalArgumentException

if the JSON format is invalid

setLoggingEnabled

public static void setLoggingEnabled(boolean loggingEnabled)

Globally enables / disables Cloud Firestore logging for the SDK.

terminate

public @NonNullTask<Voidterminate()

Terminates thisFirebaseFirestore instance.

After callingterminate() only theclearPersistence method may be used. Any other method will throw anIllegalStateException.

To restart after termination, simply create a new instance ofFirebaseFirestore withgetInstance orgetInstance.

terminate() does not cancel any pending writes and any tasks that are awaiting a response from the server will not be resolved. The next time you start this instance, it will resume attempting to send these writes to the server.

Note: Under normal circumstances, callingterminate() is not required. This method is useful only when you want to force this instance to release all of its resources or in combination with clearPersistence to ensure that all local state is destroyed between test runs.

Returns
@NonNullTask<Void>

ATask that is resolved when the instance has been successfully terminated.

useEmulator

public void useEmulator(@NonNullString host, int port)

Modifies this FirebaseDatabase instance to communicate with the Cloud Firestore emulator.

Note: Call this method before using the instance to do any database operations.

Parameters
@NonNullString host

the emulator host (for example, 10.0.2.2)

int port

the emulator port (for example, 8080)

waitForPendingWrites

public @NonNullTask<VoidwaitForPendingWrites()

Waits until all currently pending writes for the active user have been acknowledged by the backend.

The returned Task completes immediately if there are no outstanding writes. Otherwise, the Task waits for all previously issued writes (including those written in a previous app session), but it does not wait for writes that were added after the method is called. If you wish to wait for additional writes, you have to callwaitForPendingWrites() again.

Any outstandingwaitForPendingWrites() Tasks are cancelled during user changes.

Returns
@NonNullTask<Void>

ATask which resolves when all currently pending writes have been acknowledged by the backend.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-07-21 UTC.