### Firestore Java Quick Start Example Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/README.md Demonstrates basic Firestore operations including initialization, reading, writing, querying, and closing the connection. Ensure FirestoreOptions are configured correctly before use. ```java // Initialize Firestore db = FirestoreOptions.getDefaultInstance().getService(); // Read DocumentSnapshot snap = db.collection("users").document("alice").get().get(); // Write db.collection("users").document("alice").set(data).get(); // Query QuerySnapshot results = db.collection("users") .where(Filter.greaterThan("age", 18)) .get() .get(); // Close db.close(); ``` -------------------------------- ### Initialize Firestore Client Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/INDEX.md Initialize the Firestore client using default instance settings. This is the most common way to get started. ```java Firestore db = FirestoreOptions.getDefaultInstance().getService(); ``` -------------------------------- ### Pagination with Start Cursor Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/quick-reference.md Retrieve documents starting from a specific value in an ordered query. ```java // Start at cursor Query queryStart = db.collection("users") .orderBy("age") .startAt(25); ``` -------------------------------- ### Initialize Firestore with Default Configuration Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Initializes Firestore using the default project ID from the environment and application default credentials. This is the simplest way to get started. ```java // Uses default project from environment and application default credentials Firestore db = FirestoreOptions.getDefaultInstance().getService(); ``` -------------------------------- ### Example: Close Firestore Client Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md An example demonstrating how to close the Firestore client and handle potential exceptions during the closing process. ```java try { db.close(); } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Execute Aggregate Queries Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/advanced-features.md Execute aggregate queries for count, sum, and average, and retrieve the results. This example demonstrates how to get the count of documents, the sum of a field, and the average of a field. ```java // Count documents AggregateQuery countQuery = db.collection("users").count(); AggregateQuerySnapshot snapshot = countQuery.get().get(); System.out.println("Total users: " + snapshot.getCount()); // Sum field AggregateQuery sumQuery = db.collection("orders").sum("total"); AggregateQuerySnapshot sumSnapshot = sumQuery.get().get(); System.out.println("Total sales: " + sumSnapshot.getDouble(AggregateField.sum("total"))); // Average field AggregateQuery avgQuery = db.collection("reviews").average("rating"); AggregateQuerySnapshot avgSnapshot = avgQuery.get().get(); System.out.println("Average rating: " + avgSnapshot.getDouble(AggregateField.average("rating"))); ``` -------------------------------- ### Example: Recursive Delete Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md An example demonstrating how to recursively delete a collection and wait for the operation to complete. Ensure to handle potential exceptions. ```java ApiFuture future = db.recursiveDelete(db.collection("users")); future.get(); // Wait for completion ``` -------------------------------- ### Update Document Fields Example Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Example of updating multiple fields in a document using field names and values. ```java batch.update(userRef, "age", 26, "city", "New York"); ``` -------------------------------- ### Firestore Beam Write Example Java Source: https://github.com/googleapis/java-firestore/blob/main/README.md Example demonstrating how to write data to Firestore using Apache Beam in Java. This is useful for batch data loading and synchronization. ```java /** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.firestore.beam; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.FirestoreOptions; public class ExampleFirestoreBeamWrite { public static void main(String[] args) throws Exception { // TODO(developer): Set your project ID here. // String projectId = "your-project-id"; // FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance().toBuilder() // .setProjectId(projectId) // .build(); // Firestore db = firestoreOptions.getService(); System.out.println("Hello World!"); // db.close(); } } ``` -------------------------------- ### ExplainOptions Constructor Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/advanced-features.md Options for the explain() method to get query execution statistics. This constructor initializes the ExplainOptions object. ```APIDOC ## ExplainOptions Constructor ### Description Initializes a new instance of the `ExplainOptions` class. ### Method ```java public ExplainOptions() ``` ``` -------------------------------- ### Firestore Beam Read Example Java Source: https://github.com/googleapis/java-firestore/blob/main/README.md Example demonstrating how to read data from Firestore using Apache Beam in Java. This is useful for batch processing and data integration scenarios. ```java /** * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.firestore.beam; import com.google.cloud.firestore.FirestoreOptions; import com.google.cloud.firestore.v1.FirestoreAdminClient; import com.google.cloud.firestore.v1.FirestoreAdminSettings; import com.google.cloud.firestore.v1.beans.Collection; import com.google.cloud.firestore.v1.beans.Document; import com.google.cloud.firestore.v1.beans.Field; import com.google.cloud.firestore.v1.beans.Value; import com.google.cloud.firestore.v1.proto.Value.ValueType; import com.google.api.gax.rpc.FixedTransportChannelProvider; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.firestore.v1.FirestoreClient; import com.google.cloud.firestore.v1.FirestoreSettings; import com.google.cloud.firestore.v1.proto.DocumentMask; import com.google.cloud.firestore.v1.proto.DocumentProto; import com.google.cloud.firestore.v1.proto.GetDocumentRequest; import com.google.cloud.firestore.v1.proto.StructuredQuery; import com.google.cloud.firestore.v1.proto.StructuredQuery.FieldFilter.Operator; import com.google.cloud.firestore.v1.proto.StructuredQuery.Order; import com.google.cloud.firestore.v1.proto.StructuredQuery.FieldFilter; import com.google.cloud.firestore.v1.proto.StructuredQuery.Filter; import com.google.cloud.firestore.v1.proto.StructuredQuery.Order.Direction; import com.google.cloud.firestore.v1.proto.Value; import com.google.protobuf.Timestamp; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.auth.MoreCallCredentials; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; public class ExampleFirestoreBeamRead { public static void main(String[] args) throws Exception { // TODO(developer): Set your project ID here. // String projectId = "your-project-id"; // FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance().toBuilder() // .setProjectId(projectId) // .build(); // Firestore db = firestoreOptions.getService(); System.out.println("Hello World!"); // db.close(); } } ``` -------------------------------- ### ExplainOptions.setAnalyze Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/advanced-features.md Configures whether to execute the query or just analyze it to get execution statistics. ```APIDOC ## ExplainOptions.setAnalyze(analyze) ### Description Sets whether to execute the query or just analyze it to obtain query execution statistics. ### Method ```java ExplainOptions setAnalyze(boolean analyze) ``` ### Parameters #### Path Parameters - **analyze** (boolean) - Required - True to execute and collect stats, false for plan only ### Returns - `ExplainOptions` - This options object (for chaining). ### Request Example ```java // Get execution plan without running the query ExplainResults plan = db.collection("users") .explain(new ExplainOptions().setAnalyze(false)) .get(); System.out.println("Query plan: " + plan.getPlan()); ``` ``` -------------------------------- ### Pagination with Start After Cursor Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/quick-reference.md Retrieve documents immediately following a specific document snapshot in an ordered query. ```java // Start after cursor Query queryAfter = db.collection("users") .orderBy("age") .startAfter(snapshot); ``` -------------------------------- ### Obtain BulkWriter with Default Options Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Instantiate a BulkWriter using the default configuration. This is the simplest way to start performing batched writes. ```java BulkWriter writer = db.bulkWriter(); ``` -------------------------------- ### Write Example Data to Firestore with Beam Source: https://github.com/googleapis/java-firestore/blob/main/samples/snippets/src/main/java/com/example/firestore/beam/README.md Execute this Maven command to run the `ExampleFirestoreBeamWrite` job. This writes sample data to the 'cities-beam-sample' collection in Firestore. ```bash mvn compile exec:java@beam-sample -Dexec.mainClass=com.example.firestore.beam.ExampleFirestoreBeamWrite \ "-Dexec.args=--project=$GOOGLE_CLOUD_PROJECT \ --runner=DataflowRunner \ --region=$REGION \ --tempLocation=$TEMP_LOCATION \ --numWorkers=$NUM_WORKERS \ --maxNumWorkers=$MAX_NUM_WORKERS" ``` -------------------------------- ### Example: Accessing Write Result Timestamp Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Demonstrates how to get the update time from a WriteResult object after a future operation completes. ```java WriteResult result = future.get(); System.out.println("Updated at: " + result.getUpdateTime()); ``` -------------------------------- ### batch Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Gets a `WriteBatch` instance that can be used to combine multiple writes. ```APIDOC ## batch() ### Description Gets a `WriteBatch` instance that can be used to combine multiple writes. ### Method Signature ```java WriteBatch batch() ``` ### Returns `WriteBatch` - A batch object for atomic multi-write operations. ### Example ```java WriteBatch batch = db.batch(); batch.set(db.collection("users").document("alice"), data1); batch.update(db.collection("users").document("bob"), data2); ApiFuture> result = batch.commit(); ``` ``` -------------------------------- ### Iterate and Print Documents from QuerySnapshot Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md An example demonstrating how to retrieve a QuerySnapshot and then iterate through its documents, printing their IDs and data. ```java QuerySnapshot snapshot = query.get().get(); for (QueryDocumentSnapshot doc : snapshot.getDocuments()) { System.out.println(doc.getId() + " => " + doc.getData()); } ``` -------------------------------- ### get() Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Reads the document referred to by this DocumentReference. ```APIDOC ## get() ### Description Reads the document referred to by this DocumentReference. ### Method get ### Response #### Success Response (200) - **DocumentSnapshot** - A future that resolves to a DocumentSnapshot. ### Example ```java ApiFuture future = docRef.get(); DocumentSnapshot snapshot = future.get(); if (snapshot.exists()) { System.out.println("Document exists with data: " + snapshot.getData()); } else { System.out.println("Document does not exist"); } ``` ``` -------------------------------- ### Obtain a WriteBatch Instance Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Get an instance of WriteBatch to group multiple write operations. ```java WriteBatch batch = db.batch(); ``` -------------------------------- ### get() Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/advanced-features.md Executes the aggregate query and returns a future that resolves to the aggregate result snapshot. ```APIDOC ## get() Executes the aggregate query. ```java ApiFuture get() ``` **Returns:** `ApiFuture` — A future resolving to the aggregate result. **Example:** ```java // Count documents AggregateQuery countQuery = db.collection("users").count(); AggregateQuerySnapshot snapshot = countQuery.get().get(); System.out.println("Total users: " + snapshot.getCount()); // Sum field AggregateQuery sumQuery = db.collection("orders").sum("total"); AggregateQuerySnapshot sumSnapshot = sumQuery.get().get(); System.out.println("Total sales: " + sumSnapshot.getDouble(AggregateField.sum("total"))); // Average field AggregateQuery avgQuery = db.collection("reviews").average("rating"); AggregateQuerySnapshot avgSnapshot = avgQuery.get().get(); System.out.println("Average rating: " + avgSnapshot.getDouble(AggregateField.average("rating"))); ``` ``` -------------------------------- ### get() Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/query-and-collection.md Retrieves all documents matching the query. Returns a future that resolves to a QuerySnapshot. ```APIDOC ## get() ### Description Retrieves all documents matching the query. ### Returns `ApiFuture` — A future resolving to a QuerySnapshot. ### Example ```java ApiFuture future = db.collection("users") .where(Filter.greaterThan("age", 18)) .get(); QuerySnapshot snapshot = future.get(); for (QueryDocumentSnapshot doc : snapshot.getDocuments()) { System.out.println(doc.getId() + " => " + doc.getData()); } ``` ``` -------------------------------- ### Get Firestore Service Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Creates and returns a Firestore instance from the provided options. Use this when you need to explicitly configure project ID and other settings. ```java FirestoreOptions options = FirestoreOptions.newBuilder() .setProjectId("my-project") .build(); Firestore db = options.getService(); ``` -------------------------------- ### Configure ExplainOptions for Query Analysis Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/advanced-features.md Set the 'analyze' option to false to get the query execution plan without running the query. This is useful for understanding query performance characteristics. ```java ExplainOptions setAnalyze(boolean analyze) ``` ```java // Get execution plan without running the query ExplainResults plan = db.collection("users") .explain(new ExplainOptions().setAnalyze(false)) .get(); System.out.println("Query plan: " + plan.getPlan()); ``` -------------------------------- ### Start Firestore Query at Specific Field Values Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/query-and-collection.md Use `startAt()` with field values to create a cursor positioned at the document matching those values. Requires an `orderBy()` clause. ```java Query q = db.collection("users") .orderBy("age") .startAt(25); ``` -------------------------------- ### Initialize ExplainOptions Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/advanced-features.md Use the default constructor to create an ExplainOptions object. This object is used to configure query execution analysis. ```java public ExplainOptions() ``` -------------------------------- ### Build Samples with Service Account Source: https://github.com/googleapis/java-firestore/blob/main/CONTRIBUTING.md Use this command to build samples that require access to GCP services, ensuring the service account credentials are set. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account.json mvn clean verify ``` -------------------------------- ### Build and Run Unit Tests Source: https://github.com/googleapis/java-firestore/blob/main/CONTRIBUTING.md Execute this command to clean, verify, and run all unit tests for the project. ```bash mvn clean verify ``` -------------------------------- ### Query a Collection Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/INDEX.md Query a collection with filters and ordering, limiting the results. This example filters for users older than 18 and orders by age. ```java QuerySnapshot snapshot = db.collection("users") .where(Filter.greaterThan("age", 18)) .orderBy("age") .limit(10) .get() .get(); ``` -------------------------------- ### Get Parent Collection - Java Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Get a reference to the collection that contains this document. This is useful for navigating the Firestore hierarchy. ```java CollectionReference getParent() // Example: CollectionReference parent = docRef.getParent(); ``` -------------------------------- ### Create Firestore Options Builder Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Get a builder to create customized FirestoreOptions. Use this when you need to configure specific settings for your Firestore instance. ```java FirestoreOptions.newBuilder() ``` -------------------------------- ### Query.startAt(DocumentSnapshot) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/query-and-collection.md Creates a query cursor positioned at the given document snapshot. ```APIDOC ## Query.startAt(DocumentSnapshot) ### Description Creates a cursor positioned at the given document snapshot. ### Method `Query startAt(@Nonnull DocumentSnapshot snapshot)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```java // Assuming 'snapshot' is a DocumentSnapshot object Query q = db.collection("users").startAt(snapshot); ``` ### Response #### Success Response (200) - `Query` - A new query starting at the cursor. #### Response Example None provided. ``` -------------------------------- ### Format Code with google-java-format Source: https://github.com/googleapis/java-firestore/blob/main/CONTRIBUTING.md Run this Maven command to format your project's code according to the google-java-format standard. ```bash mvn com.spotify.fmt:fmt-maven-plugin:format ``` -------------------------------- ### Query.startAt(Object...) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/query-and-collection.md Creates a query cursor positioned at documents with the given field values. ```APIDOC ## Query.startAt(Object...) ### Description Creates a cursor positioned at the document with the given field values. ### Method `Query startAt(Object... fieldValues)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```java Query q = db.collection("users") .orderBy("age") .startAt(25); ``` ### Response #### Success Response (200) - `Query` - A new query starting at the cursor. #### Response Example None provided. ``` -------------------------------- ### Get Specific Field Value Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Access the value of a specific field within the document using its path. The get() method returns the value as an Object, which may require casting to the expected type. It returns null if the field does not exist. ```java String name = (String) snapshot.get("name"); Long age = (Long) snapshot.get("age"); String city = (String) snapshot.get("address.city"); ``` -------------------------------- ### getParent() Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Gets a reference to the parent collection of this document. ```APIDOC ## getParent() ### Description A reference to the Collection to which this DocumentReference belongs. ### Method Signature ```java CollectionReference getParent() ``` ### Returns `CollectionReference` — The parent collection. ### Example ```java CollectionReference parent = docRef.getParent(); ``` ``` -------------------------------- ### Create and Serialize FirestoreBundle Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/advanced-features.md Demonstrates the complete process of building a FirestoreBundle with specific queries and documents, then retrieving it as a ByteString for client use. ```java FirestoreBundle bundle = db.bundleBuilder("initial-load") .addQuery(db.collection("posts").limit(100)) .addDocument(db.collection("config").document("settings")) .build(); ByteString buffer = bundle.getAsBuffer(); // Send buffer to client ``` -------------------------------- ### Start Firestore Query After Specific Field Values Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/query-and-collection.md Use `startAfter()` with field values to create a cursor positioned immediately after the document matching those values. Requires an `orderBy()` clause. ```java Query q = db.collection("users") .orderBy("age") .startAfter(25); ``` -------------------------------- ### Obtain BulkWriter with Custom Options Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Instantiate a BulkWriter with custom options, allowing for fine-grained control over write behavior. ```java BulkWriter writer = db.bulkWriter(options); ``` -------------------------------- ### Get Document ID Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieve the unique identifier for the document. ```java String getId() ``` -------------------------------- ### getId() Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/query-and-collection.md Gets the ID of the collection, which is the last component of its path. ```APIDOC ## getId() ### Description The ID of the collection (the last component of the path). ### Returns `String` — The collection ID. ``` -------------------------------- ### Get Query from QuerySnapshot Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieves the original query that produced this snapshot. ```java Query getQuery() ``` -------------------------------- ### Initialize Firestore with Multi-Database Support Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Connects to a secondary or specific database within a project. This is useful for managing multiple distinct datasets within the same project. ```java // Connect to a secondary database Firestore db = FirestoreOptions.newBuilder() .setProjectId("my-project") .setDatabaseId("secondary-db") .build() .getService(); ``` -------------------------------- ### Firestore Snapshot Listener Example Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Implements an EventListener to handle document snapshot updates and errors. Remember to remove the listener registration when it's no longer needed to prevent memory leaks. ```java EventListener listener = (snapshot, error) -> { if (error != null) { System.err.println("Listen failed: " + error); return; } if (snapshot != null && snapshot.exists()) { System.out.println("Current data: " + snapshot.getData()); } else { System.out.println("Current data: null"); } }; ListenerRegistration registration = docRef.addSnapshotListener(listener); // Later, remove the listener registration.remove(); ``` -------------------------------- ### Get Size of QuerySnapshot Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Returns the number of documents contained within this snapshot. ```java int size() ``` -------------------------------- ### Initialize Firestore with Emulator Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Configures Firestore to connect to a local emulator for development. This allows for testing without incurring cloud costs or affecting production data. ```java // Option 1: Via builder Firestore db = FirestoreOptions.newBuilder() .setProjectId("test-project") .setEmulatorHost("localhost:8080") .build() .getService(); // Option 2: Via environment variable // export FIRESTORE_EMULATOR_HOST=localhost:8080 Firestore db = FirestoreOptions.getDefaultInstance().getService(); ``` -------------------------------- ### Get Document Reference Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Obtain a DocumentReference object pointing to this specific document. ```java DocumentReference getReference() ``` -------------------------------- ### Create BulkWriter with Options Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Creates a BulkWriter instance with custom configuration options. This allows for customized throttling and callbacks during bulk write operations. ```java BulkWriter bulkWriter(@Nonnull BulkWriterOptions options) ``` -------------------------------- ### BulkWriterOptions Constructor Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Initializes a new BulkWriterOptions object with default settings. ```APIDOC ## BulkWriterOptions() ### Description Initializes a new `BulkWriterOptions` object. ### Constructor `public BulkWriterOptions()` ``` -------------------------------- ### Get Current Timestamp Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/types-and-values.md Obtain the current server time using `Timestamp.now()`. ```java Timestamp.now() ``` -------------------------------- ### collection(collectionPath) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Gets a CollectionReference instance that refers to the collection that is a child of this document. ```APIDOC ## collection(collectionPath) ### Description Gets a `CollectionReference` instance that refers to the collection that is a child of this document. ### Method Signature ```java CollectionReference collection(@Nonnull String collectionPath) ``` ### Parameters #### Path Parameters - **collectionPath** (String) - Required - A relative slash-separated path to a collection (e.g., "posts" or "posts/post1/comments") ### Returns `CollectionReference` — The subcollection reference. ### Example ```java CollectionReference posts = docRef.collection("posts"); ``` ``` -------------------------------- ### getPath() Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/query-and-collection.md Gets a string representing the path of the collection relative to the root of the database. ```APIDOC ## getPath() ### Description A string representing the path of the collection relative to the root of the database. ### Returns `String` — The slash-separated path. ``` -------------------------------- ### Query.startAfter(Object...) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/query-and-collection.md Creates a query cursor positioned after documents with the given field values. ```APIDOC ## Query.startAfter(Object...) ### Description Creates a cursor positioned after the document with the given field values. ### Method `Query startAfter(Object... fieldValues)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```java Query q = db.collection("users") .orderBy("age") .startAfter(25); ``` ### Response #### Success Response (200) - `Query` - A new query starting after the cursor. #### Response Example None provided. ``` -------------------------------- ### Build and Run Integration Tests Source: https://github.com/googleapis/java-firestore/blob/main/CONTRIBUTING.md Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to your service account JSON file before running this command to include integration tests. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account.json mvn -Penable-integration-tests clean verify ``` -------------------------------- ### get(fieldMask) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Reads the document while optionally applying a field mask to reduce data transmission. ```APIDOC ## get(fieldMask) ### Description Reads the document while optionally applying a field mask to reduce data transmission. ### Method get ### Parameters #### Request Body - **fieldMask** (FieldMask) - Required - Specifies the subset of fields to return ### Response #### Success Response (200) - **DocumentSnapshot** - A future that resolves to a DocumentSnapshot with only the specified fields. ``` -------------------------------- ### Get Document Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Reads the document referred to by this DocumentReference. Use this to retrieve the current state of a document. ```java ApiFuture future = docRef.get(); DocumentSnapshot snapshot = future.get(); if (snapshot.exists()) { System.out.println("Document exists with data: " + snapshot.getData()); } else { System.out.println("Document does not exist"); } ``` -------------------------------- ### Get Write Update Time Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Retrieves the timestamp when a write operation was committed. Useful for logging or auditing. ```java Timestamp getUpdateTime() ``` -------------------------------- ### Initialize Client Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/INDEX.md Initializes the Firestore client using default options. This client is used to interact with Firestore. ```APIDOC ## Initialize Client ### Description Initializes the Firestore client using default options. This client is used to interact with Firestore. ### Code ```java Firestore db = FirestoreOptions.getDefaultInstance().getService(); ``` ``` -------------------------------- ### Authenticate from Service Account File Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/INDEX.md Authenticate using credentials from a service account JSON file. Ensure the file path is correct. ```java // From service account file GoogleCredentials creds = GoogleCredentials.fromStream( new FileInputStream("service-account.json") ); ``` -------------------------------- ### Get FirestoreBundle as ByteString Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/advanced-features.md Serializes the FirestoreBundle into a ByteString, which is suitable for network transmission to clients for offline access. ```java ByteString getAsBuffer() ``` -------------------------------- ### Get Documents from QuerySnapshot Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieves a list of all documents present in this snapshot. This is useful for iterating through the query results. ```java List getDocuments() ``` -------------------------------- ### getList(field) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Gets the value of the field as a List. This method is suitable for retrieving array data from Firestore. ```APIDOC ## getList(field) ### Description Gets the value of the field as a List. ### Method ```java List getList(@Nonnull String field) ``` ### Parameters #### Path Parameters - **field** (String) - Required - The field path ### Returns - **List** - The list value, or null. ``` -------------------------------- ### Initialize Firestore with OpenTelemetry Tracing Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Enables OpenTelemetry metrics and tracing for Firestore operations. This is valuable for monitoring and performance analysis in production environments. ```java FirestoreOpenTelemetryOptions telemetryOptions = new FirestoreOpenTelemetryOptions() .setMetricsEnabled(true) .setTracingEnabled(true); Firestore db = FirestoreOptions.newBuilder() .setProjectId("my-project") .setOpenTelemetryOptions(telemetryOptions) .build() .getService(); ``` -------------------------------- ### Get Snapshot Read Time Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieve the Timestamp indicating when this specific snapshot of the document was read from the database. ```java Timestamp getReadTime() ``` -------------------------------- ### create(pojo) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Creates a new Document at the DocumentReference location using a POJO. Fails if the document already exists. ```APIDOC ## create(pojo) ### Description Creates a new Document at the DocumentReference location using a POJO. Fails if the document already exists. ### Method Signature ```java ApiFuture create(@Nonnull Object pojo) ``` ### Parameters #### Request Body - **pojo** (Object) - Required - The POJO that will be used to populate the document ### Returns `ApiFuture` — A future that resolves when the write completes. ### Example ```java User user = new User("Alice", 25); ApiFuture future = docRef.create(user); ``` ``` -------------------------------- ### Read and Filter Data from Firestore with Beam Source: https://github.com/googleapis/java-firestore/blob/main/samples/snippets/src/main/java/com/example/firestore/beam/README.md Run this Maven command to execute the `ExampleFirestoreBeamRead` job. It filters and reads data from the 'cities-beam-sample' collection in Firestore. ```bash mvn compile exec:java@beam-sample -Dexec.mainClass=com.example.firestore.beam.ExampleFirestoreBeamRead \ "-Dexec.args=--project=$GOOGLE_CLOUD_PROJECT \ --runner=DataflowRunner \ --region=$REGION \ --tempLocation=$TEMP_LOCATION \ --numWorkers=$NUM_WORKERS \ --maxNumWorkers=$MAX_NUM_WORKERS" ``` -------------------------------- ### Get Timestamp Nanos Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/types-and-values.md Retrieve the nanoseconds component of a `Timestamp` object, representing the fractional part of a second. ```java Timestamp.getNanos() ``` -------------------------------- ### Get Timestamp Seconds Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/types-and-values.md Retrieve the seconds component of a `Timestamp` object, representing seconds since the epoch. ```java Timestamp.getSeconds() ``` -------------------------------- ### bulkWriter(options) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Creates a BulkWriter instance with custom configuration options, allowing for tailored behavior in parallel writes. ```APIDOC ## bulkWriter(options) ### Description Creates a `BulkWriter` instance with custom configuration options. ### Parameters #### Request Body - **options** (BulkWriterOptions) - Required - Configuration for BulkWriter behavior ### Returns `BulkWriter` — A bulk writer with custom settings. ``` -------------------------------- ### Get Document Changes from QuerySnapshot Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieves a list of changes (added, modified, removed) that occurred for the documents in this snapshot. ```java List getChanges() ``` -------------------------------- ### Build Firestore Options Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Build the FirestoreOptions object after configuring all desired settings. ```java FirestoreOptions build() ``` -------------------------------- ### create(fields) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Creates a new Document at the DocumentReference location. Fails if the document already exists. ```APIDOC ## create(fields) ### Description Creates a new Document at the DocumentReference location. Fails if the document already exists. ### Method Signature ```java ApiFuture create(@Nonnull Map fields) ``` ### Parameters #### Request Body - **fields** (Map) - Required - A map of the fields and values for the document ### Returns `ApiFuture` — A future that resolves when the write completes. ### Throws `FirestoreException` if the document already exists. ### Example ```java Map data = new HashMap<>(); data.put("name", "Alice"); data.put("age", 25); ApiFuture future = docRef.create(data); WriteResult result = future.get(); System.out.println("Created at: " + result.getUpdateTime()); ``` ``` -------------------------------- ### getBlob(field) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Gets the value of the field as a Blob. Use this method to retrieve binary data stored in Firestore. ```APIDOC ## getBlob(field) ### Description Gets the value of the field as a Blob. ### Method ```java Blob getBlob(@Nonnull String field) ``` ### Parameters #### Path Parameters - **field** (String) - Required - The field path ### Returns - **Blob** - The Blob value, or null. ``` -------------------------------- ### getGeoPoint(field) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Gets the value of the field as a GeoPoint. This method is useful for retrieving geographical data stored in Firestore. ```APIDOC ## getGeoPoint(field) ### Description Gets the value of the field as a GeoPoint. ### Method ```java GeoPoint getGeoPoint(@Nonnull String field) ``` ### Parameters #### Path Parameters - **field** (String) - Required - The field path ### Returns - **GeoPoint** - The GeoPoint value, or null. ``` -------------------------------- ### Get Blob from Field Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieves the value of a specified field as a Blob. Returns null if the field does not exist or is not a Blob. ```java Blob getBlob(@Nonnull String field) ``` -------------------------------- ### Build Data Pipeline Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Creates a new `PipelineSource` to define and execute a data pipeline. Pipelines operate on a request/response basis and do not use the local SDK cache or support real-time listeners. ```java Pipeline pipeline = db.pipeline() .collection("books") .where(Field("rating").isGreaterThan(4.5)) .sort(Field("rating").descending()) .limit(2); ``` -------------------------------- ### Listen for Realtime Changes Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/INDEX.md Listen for changes to a document in realtime. A listener registration is returned, which can be used to stop listening. ```java ListenerRegistration reg = docRef.addSnapshotListener((snap, error) -> { if (error != null) return; System.out.println("Updated: " + snap.getData()); }); reg.remove(); // Stop listening ``` -------------------------------- ### Get GeoPoint from Field Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieves the value of a specified field as a GeoPoint. Returns null if the field does not exist or is not a GeoPoint. ```java GeoPoint getGeoPoint(@Nonnull String field) ``` -------------------------------- ### Create BulkWriter Instance Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Creates a BulkWriter instance for performing multiple writes in parallel. It gradually ramps up writes following the 500/50/5 rule. ```java BulkWriter bulkWriter() ``` -------------------------------- ### Get Subcollection Reference Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Obtain a reference to a subcollection within a document. Use a relative path to specify the subcollection. ```java CollectionReference posts = docRef.collection("posts"); ``` -------------------------------- ### Get Document ID - Java Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Retrieve the unique identifier for a document. This is the last component of the document's path. ```java String getId() // Example: DocumentReference docRef = db.collection("users").document("alice"); String docId = docRef.getId(); // Returns "alice" ``` -------------------------------- ### Create GeoPoint Instance Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/types-and-values.md Instantiate a GeoPoint with latitude and longitude. Latitude must be between -90 and 90, and longitude between -180 and 180. ```java GeoPoint location = new GeoPoint(37.7749, -122.4194); // San Francisco ``` -------------------------------- ### document(path) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Gets a DocumentReference that refers to the document at the specified path. This allows direct access to individual documents. ```APIDOC ## document(path) ### Description Gets a `DocumentReference` that refers to the document at the specified path. ### Method ```java DocumentReference document(@Nonnull String path) ``` ### Parameters #### Path Parameters - **path** (String) - Required - A slash-separated path to a document (e.g., "users/user1" or "users/user1/posts/post1") ### Returns `DocumentReference` - A reference to the specified document. ### Example ```java DocumentReference userRef = db.document("users/alice"); ``` ``` -------------------------------- ### FirestoreOptions.newBuilder() Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Initializes a builder to create customized FirestoreOptions with specific configurations. ```APIDOC ## FirestoreOptions.newBuilder() ### Description Returns a builder for creating customized options. ### Method `static Builder newBuilder()` ### Returns `Builder` — A builder for configuring options. ``` -------------------------------- ### build Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Builds and returns the configured FirestoreOptions object. This is the final step in the builder pattern. ```APIDOC ## build() ### Description Builds the FirestoreOptions object. ### Method FirestoreOptions build() ### Response #### Success Response - **FirestoreOptions** - A configured options object. ``` -------------------------------- ### Get Firestore Exception Message Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/errors-and-exceptions.md Retrieves the descriptive error message from a FirestoreException. Use this to understand the nature of the error. ```java String getMessage() ``` -------------------------------- ### Listen for Changes Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/INDEX.md Sets up a listener to receive real-time updates for a document. The listener is invoked whenever the document changes. It can be removed to stop listening. ```APIDOC ## Listen for Changes ### Description Sets up a listener to receive real-time updates for a document. The listener is invoked whenever the document changes. It can be removed to stop listening. ### Code ```java ListenerRegistration reg = docRef.addSnapshotListener((snap, error) -> { if (error != null) return; System.out.println("Updated: " + snap.getData()); }); reg.remove(); // Stop listening ``` ``` -------------------------------- ### Get List from Field Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieves the value of a specified field as a List of Objects. Returns null if the field does not exist or is not a List. ```java List getList(@Nonnull String field) ``` -------------------------------- ### Listen for Real-time Document Updates Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/quick-reference.md Set up a listener to receive real-time updates for a specific document. The listener is invoked whenever the document changes. Remember to remove the listener when it's no longer needed to prevent memory leaks. ```java ListenerRegistration registration = docRef.addSnapshotListener((snapshot, error) -> { if (error != null) { System.err.println("Listen failed: " + error); return; } if (snapshot != null && snapshot.exists()) { System.out.println("Updated: " + snapshot.getData()); } }); // Stop listening registration.remove(); ``` -------------------------------- ### Get Document Creation Time Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieve the Timestamp indicating when the document was initially created. Returns null if the document does not exist. ```java Timestamp getCreateTime() ``` -------------------------------- ### create(documentRef, fields) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Creates a new document with the specified fields. This operation will fail if the document already exists. ```APIDOC ## create(documentRef, fields) ### Description Creates a new document referred to by documentRef. Fails if the document exists. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **documentRef** (DocumentReference) - Required - The document to create - **fields** (Map) - Required - The document data ### Response #### Success Response - **WriteBatch** - This WriteBatch instance (for chaining). ### Error Handling Fails if the document exists. ``` -------------------------------- ### Create GeoPoint Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/quick-reference.md Instantiate a GeoPoint with latitude and longitude, and add it to data for storage. ```java GeoPoint location = new GeoPoint(37.7749, -122.4194); data.put("location", location); GeoPoint retrieved = (GeoPoint) snapshot.get("location"); double lat = retrieved.getLatitude(); double lon = retrieved.getLongitude(); ``` -------------------------------- ### Get Field as Long Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieve the value of a specified field directly as a Long. Returns null if the field does not exist or is not a long. ```java Long getLong(@Nonnull String field) ``` -------------------------------- ### Get Field as Double Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieve the value of a specified field directly as a Double. Returns null if the field does not exist or is not a double. ```java Double getDouble(@Nonnull String field) ``` -------------------------------- ### explain(options) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/advanced-features.md Retrieves execution statistics for the aggregate query without actually executing it, useful for performance analysis. ```APIDOC ## explain(options) Gets execution statistics for the aggregate query without executing it. ```java ApiFuture> explain(ExplainOptions options) ``` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | ExplainOptions | Yes | — | Explain options | **Returns:** `ApiFuture>` — Execution statistics. ``` -------------------------------- ### bulkWriter() Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Creates a BulkWriter instance for performing multiple writes in parallel. It gradually ramps up writes following the 500/50/5 rule. ```APIDOC ## bulkWriter() ### Description Creates a `BulkWriter` instance for performing multiple writes in parallel. Gradually ramps up writes following the 500/50/5 rule. ### Returns `BulkWriter` — A bulk writer for parallel writes. ### See Also [Ramping up traffic](https://cloud.google.com/firestore/docs/best-practices#ramping_up_traffic) ``` -------------------------------- ### Get Field as Boolean Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieve the value of a specified field directly as a Boolean. Returns null if the field does not exist or is not a boolean. ```java Boolean getBoolean(@Nonnull String field) ``` -------------------------------- ### Set Initial Operations Per Second Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Sets the initial operations per second for the BulkWriter. Returns the options object for chaining. ```java BulkWriterOptions setInitialOpsPerSecond(int opsPerSecond) ``` -------------------------------- ### Get Field as String Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieve the value of a specified field directly as a String. Returns null if the field does not exist or is not a string. ```java String getString(@Nonnull String field) ``` -------------------------------- ### Configure Firestore with Custom Credentials Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/INDEX.md Build custom Firestore options, specifying the project ID and custom credentials. This allows for fine-grained control over the client configuration. ```java // Custom credentials FirestoreOptions options = FirestoreOptions.newBuilder() .setProjectId("my-project") .setCredentials(creds) .build(); ``` -------------------------------- ### Get Multiple Documents Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Retrieve a list of documents from Firestore using their references. The result is a future that resolves to a list of DocumentSnapshots. ```java ApiFuture> future = db.getAll( db.document("users/alice"), db.document("users/bob") ); List snapshots = future.get(); ``` -------------------------------- ### collection(path) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Gets a CollectionReference that refers to the collection at the specified path. This is used to access and manipulate collections within Firestore. ```APIDOC ## collection(path) ### Description Gets a `CollectionReference` that refers to the collection at the specified path. ### Method ```java CollectionReference collection(@Nonnull String path) ``` ### Parameters #### Path Parameters - **path** (String) - Required - A slash-separated path to a collection (e.g., "users" or "users/user1/posts") ### Returns `CollectionReference` - A reference to the specified collection. ### Example ```java Firestore db = FirestoreOptions.getDefaultInstance().getService(); CollectionReference usersRef = db.collection("users"); ``` ``` -------------------------------- ### Get Document Reference Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Obtain a reference to a specific document using its slash-separated path. This can be a document in a root collection or a subcollection. ```java DocumentReference userRef = db.document("users/alice"); ``` -------------------------------- ### create(documentRef, fields) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Creates a new document. Fails if the document exists. ```APIDOC ## create(documentRef, fields) ### Description Creates a new document. Fails if the document exists. ### Method create ### Parameters #### Path Parameters * **documentRef** (DocumentReference) - Required - The document to create * **fields** (Map) - Required - The document data ### Response #### Success Response (200) * **WriteResult** - A future resolving to the WriteResult. ``` -------------------------------- ### Initialize Firestore: With Project ID Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/quick-reference.md Initialize Firestore by explicitly setting the project ID. Use this when your application needs to target a specific Google Cloud project. ```java Firestore db = FirestoreOptions.newBuilder() .setProjectId("my-project") .build() .getService(); ``` -------------------------------- ### Get Firestore Exception Code Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/errors-and-exceptions.md Retrieves the gRPC status code associated with a FirestoreException. This is useful for programmatic error handling. ```java int getCode() ``` -------------------------------- ### set(pojo, options) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Overwrites or merges the document with the provided POJO based on SetOptions. ```APIDOC ## set(pojo, options) ### Description Overwrites or merges the document with the provided POJO based on SetOptions. ### Method Signature ```java ApiFuture set(@Nonnull Object pojo, @Nonnull SetOptions options) ``` ### Parameters #### Request Body - **pojo** (Object) - Required - The POJO to write to the document - **options** (SetOptions) - Required - Configuration for merge behavior ### Returns `ApiFuture` — A future that resolves when the write completes. ``` -------------------------------- ### Set Document (Create or Overwrite) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/quick-reference.md Use `set()` to create a new document or overwrite an existing one with the provided data. Ensure the `ApiFuture` is handled to confirm the write operation. ```java Map data = new HashMap<>(); data.put("name", "Alice"); data.put("age", 25); ApiFuture future = db.collection("users").document("alice").set(data); future.get(); ``` -------------------------------- ### Get Field as Timestamp Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/snapshots-and-listeners.md Retrieve the value of a specified field directly as a Timestamp object. Returns null if the field does not exist or is not a Timestamp. ```java Timestamp getTimestamp(@Nonnull String field) ``` -------------------------------- ### Create Document with Map Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Create a new document at the specified reference location using a map of fields. This operation fails if the document already exists. Ensure the document does not already exist to avoid exceptions. ```java Map data = new HashMap<>(); data.put("name", "Alice"); data.put("age", 25); ApiFuture future = docRef.create(data); WriteResult result = future.get(); System.out.println("Created at: " + result.getUpdateTime()); ``` -------------------------------- ### Get Firestore Instance - Java Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Access the Firestore database instance associated with this document reference. This is necessary for performing database operations. ```java Firestore getFirestore() // Example: Firestore firestore = docRef.getFirestore(); ``` -------------------------------- ### Get Document Path - Java Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/document-reference.md Obtain the string representation of the document's location relative to the database root. Paths are slash-separated. ```java String getPath() // Example: String path = docRef.getPath(); // Returns "users/alice" ``` -------------------------------- ### pipeline() Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Creates a new PipelineSource to build and execute a data pipeline. Pipelines are composed of a sequence of stages for processing data. ```APIDOC ## pipeline() ### Description Creates a new `PipelineSource` to build and execute a data pipeline. A pipeline is composed of a sequence of stages, where each stage processes the output from the previous one. ### Method ```java PipelineSource pipeline() ``` ### Returns `PipelineSource` - A builder to define pipeline stages. ### Note Pipelines operate on a request/response basis only. They do not utilize the local SDK cache or support realtime snapshot listeners. ### Example ```java Pipeline pipeline = db.pipeline() .collection("books") .where(Field("rating").isGreaterThan(4.5)) .sort(Field("rating").descending()) .limit(2); ``` ``` -------------------------------- ### Get Multiple Documents with Field Mask Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Retrieve a subset of fields from multiple documents using a FieldMask. This can reduce data transfer. ```java db.getAll( new DocumentReference[]{ref1, ref2}, null, new ApiStreamObserver() { @Override public void onNext(DocumentSnapshot snapshot) { System.out.println("Got: " + snapshot.getId()); } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() {} } ); ``` -------------------------------- ### Default BulkWriterOptions Constructor Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/write-operations.md Creates a new BulkWriterOptions object with default settings. ```java public BulkWriterOptions() ``` -------------------------------- ### Create Document (Fails if Exists) Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/quick-reference.md Use `create()` to add a new document only if it does not already exist. This operation will fail if a document with the specified ID is already present. ```java db.collection("users").document("bob").create(data).get(); ``` -------------------------------- ### Get Collection Reference Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/firestore-interface.md Use this method to obtain a reference to a specific collection at a given path. The path can be for a root collection or a subcollection. ```java Firestore db = FirestoreOptions.getDefaultInstance().getService(); CollectionReference usersRef = db.collection("users"); ``` -------------------------------- ### Get Firestore Emulator Host Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Retrieves the emulator host if it has been set. This is primarily used for local development and testing against a Firestore emulator. ```java String getEmulatorHost() ``` -------------------------------- ### Get Firestore Database ID Source: https://github.com/googleapis/java-firestore/blob/main/_autodocs/configuration.md Retrieves the database ID configured for the Firestore instance. This is useful for verifying or logging the active database. ```java String getDatabaseId() ```