FirebaseFirestore

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 functions

ListenerRegistration

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

ListenerRegistration

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

ListenerRegistration

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

WriteBatch

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

Task<Void!>

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

CollectionReference
collection(collectionPath: String)

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

Query
collectionGroup(collectionId: String)

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

Task<Void!>

Disables network access for this instance.

DocumentReference
document(documentPath: String)

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

Task<Void!>

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

FirebaseApp

Returns the FirebaseApp instance to which thisFirebaseFirestore belongs.

FirebaseFirestoreSettings

Returns the settings used by thisFirebaseFirestore object.

java-staticFirebaseFirestore

Returns the defaultFirebaseFirestore instance for the defaultFirebaseApp.

java-staticFirebaseFirestore

Returns the defaultFirebaseFirestore instance for the providedFirebaseApp.

java-staticFirebaseFirestore
getInstance(database: String)

Returns theFirebaseFirestore instance for the defaultFirebaseApp.

java-staticFirebaseFirestore
getInstance(app: FirebaseApp, database: String)

Returns theFirebaseFirestore instance for the providedFirebaseApp.

Task<Query!>

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

LoadBundleTask
loadBundle(bundleData: ByteArray)

Loads a Firestore bundle into the local cache.

LoadBundleTask
loadBundle(bundleData: ByteBuffer)

Loads a Firestore bundle into the local cache.

LoadBundleTask
loadBundle(bundleData: InputStream)

Loads a Firestore bundle into the local cache.

Task<Void!>
runBatch(batchFunction: WriteBatch.Function)

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

Task<TResult!>
<TResult>runTransaction(updateFunction: Transaction.Function<TResult!>)

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

Task<TResult!>
<TResult>runTransaction(
    options: TransactionOptions,
    updateFunction: Transaction.Function<TResult!>
)

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

Unit

Sets any custom settings used to configure thisFirebaseFirestore object.

Task<Void!>

This function is deprecated.

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

java-staticUnit
setLoggingEnabled(loggingEnabled: Boolean)

Globally enables / disables Cloud Firestore logging for the SDK.

Task<Void!>

Terminates thisFirebaseFirestore instance.

Unit
useEmulator(host: String, port: Int)

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

Task<Void!>

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

Public functions

addSnapshotsInSyncListener

fun addSnapshotsInSyncListener(runnable: Runnable): ListenerRegistration

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
runnable: Runnable

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

Returns
ListenerRegistration

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

addSnapshotsInSyncListener

fun addSnapshotsInSyncListener(activity: Activity, runnable: Runnable): ListenerRegistration

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
activity: Activity

The activity to scope the listener to.

runnable: Runnable

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

Returns
ListenerRegistration

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

addSnapshotsInSyncListener

fun addSnapshotsInSyncListener(executor: Executor, runnable: Runnable): ListenerRegistration

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
executor: Executor

The executor to use to call the listener.

runnable: Runnable

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

Returns
ListenerRegistration

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

batch

fun batch(): WriteBatch

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
WriteBatch

The created WriteBatch object.

clearPersistence

fun clearPersistence(): Task<Void!>

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
Task<Void!>

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

collection

fun collection(collectionPath: String): CollectionReference

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

Parameters
collectionPath: String

A slash-separated path to a collection.

Returns
CollectionReference

TheCollectionReference instance.

collectionGroup

fun collectionGroup(collectionId: String): Query

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

Parameters
collectionId: String

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
Query

The created Query.

disableNetwork

fun disableNetwork(): Task<Void!>

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
Task<Void!>

A Task that will be completed once networking is disabled.

document

fun document(documentPath: String): DocumentReference

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

Parameters
documentPath: String

A slash-separated path to a document.

Returns
DocumentReference

The DocumentReference instance.

enableNetwork

fun enableNetwork(): Task<Void!>

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

Returns
Task<Void!>

A Task that will be completed once networking is enabled.

getApp

fun getApp(): FirebaseApp

Returns the FirebaseApp instance to which thisFirebaseFirestore belongs.

getFirestoreSettings

fun getFirestoreSettings(): FirebaseFirestoreSettings

Returns the settings used by thisFirebaseFirestore object.

getInstance

java-static fun getInstance(): FirebaseFirestore

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

java-static fun getInstance(app: FirebaseApp): FirebaseFirestore

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
app: FirebaseApp

TheFirebaseApp instance that the returnedFirebaseFirestore instance is associated with.

getInstance

java-static fun getInstance(database: String): FirebaseFirestore

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
database: String

The database ID.

getInstance

java-static fun getInstance(app: FirebaseApp, database: String): FirebaseFirestore

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
app: FirebaseApp

TheFirebaseApp instance that the returnedFirebaseFirestore instance is associated with.

database: String

The database ID.

getNamedQuery

fun getNamedQuery(name: String): Task<Query!>

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.

loadBundle

fun loadBundle(bundleData: ByteArray): LoadBundleTask

Loads a Firestore bundle into the local cache.

Parameters
bundleData: ByteArray

A byte array representing the bundle to be loaded.

Returns
LoadBundleTask

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

loadBundle

fun loadBundle(bundleData: ByteBuffer): LoadBundleTask

Loads a Firestore bundle into the local cache.

Parameters
bundleData: ByteBuffer

A ByteBuffer representing the bundle to be loaded.

Returns
LoadBundleTask

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

loadBundle

fun loadBundle(bundleData: InputStream): LoadBundleTask

Loads a Firestore bundle into the local cache.

Parameters
bundleData: InputStream

A stream representing the bundle to be loaded.

Returns
LoadBundleTask

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

runBatch

fun runBatch(batchFunction: WriteBatch.Function): Task<Void!>

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

Parameters
batchFunction: WriteBatch.Function

The function to execute within the batch context.

Returns
Task<Void!>

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

runTransaction

fun <TResult>runTransaction(updateFunction: Transaction.Function<TResult!>): Task<TResult!>

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
updateFunction: Transaction.Function<TResult!>

The function to execute within the transaction context.

Returns
Task<TResult!>

The task returned from the updateFunction.

runTransaction

fun <TResult>runTransaction(
    options: TransactionOptions,
    updateFunction: Transaction.Function<TResult!>
): Task<TResult!>

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
options: TransactionOptions

The transaction options for controlling execution.

updateFunction: Transaction.Function<TResult!>

The function to execute within the transaction context.

Returns
Task<TResult!>

The task returned from the updateFunction.

setFirestoreSettings

fun setFirestoreSettings(settings: FirebaseFirestoreSettings): Unit

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
fun setIndexConfiguration(json: String): Task<Void!>
This function 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
json: String

The JSON format exported by the Firebase CLI.

Returns
Task<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

java-static fun setLoggingEnabled(loggingEnabled: Boolean): Unit

Globally enables / disables Cloud Firestore logging for the SDK.

terminate

fun terminate(): Task<Void!>

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
Task<Void!>

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

useEmulator

fun useEmulator(host: String, port: Int): Unit

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
host: String

the emulator host (for example, 10.0.2.2)

port: Int

the emulator port (for example, 8080)

waitForPendingWrites

fun waitForPendingWrites(): Task<Void!>

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
Task<Void!>

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

Public properties

persistentCacheIndexManager

val persistentCacheIndexManagerPersistentCacheIndexManager?

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.