Google Firestore
Since Camel 4.18
Both producer and consumer are supported
The Google Firestore component provides access to Google Cloud Firestore via the Google Cloud Firestore Java library.
Firestore is a flexible, scalable NoSQL cloud database for mobile, web, and server development. It keeps your data in sync across client apps through realtime listeners and offers offline support.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-google-firestore</artifactId>
<!-- use the same version as your Camel core version -->
<version>x.x.x</version>
</dependency> Authentication Configuration
Google Firestore component authentication is targeted for use with GCP Service Accounts. For more information, please refer to Google Firestore Quickstart.
When you have the service account key, you can provide authentication credentials to your application code. Google security credentials can be set through the component endpoint:
String endpoint = "google-firestore://myCollection?serviceAccountKey=/home/user/Downloads/my-key.json&projectId=my-project"; Or by providing the path to the GCP credentials file location:
Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS:
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"
URI Format
google-firestore://collectionName?[options]
You can append query options to the URI in the following format: ?options=value&option2=value&…
For example, to get a document from the users collection:
from("direct:start")
.setHeader("CamelGoogleFirestoreDocumentId", constant("user123"))
.to("google-firestore://users?operation=getDocumentById&serviceAccountKey=/path/to/key.json&projectId=my-project")
.to("log:result"); Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Google Firestore component supports 13 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
The component configuration. | GoogleFirestoreConfiguration | ||
The Firestore database ID. If not specified, the default database '(default)' will be used. | String | ||
Autowired The Firestore client to use for operations. | Firestore | ||
The Google Cloud project ID. If not specified, it will be determined from the service account key or environment. | String | ||
The Service account key that can be used as credentials for the Firestore client. It can be loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | String | ||
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
When true, the consumer will listen for real-time updates on the collection. | false | boolean | |
The document ID to use for document-specific operations. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Set the operation for the producer. Enum values:
| GoogleFirestoreOperations | ||
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
Used for enabling or disabling all consumer based health checks from this component. | true | boolean | |
Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | boolean |
Endpoint Options
The Google Firestore endpoint is configured using URI syntax:
google-firestore:collectionName
With the following path and query parameters:
Query Parameters (27 parameters)
| Name | Description | Default | Type |
|---|---|---|---|
The Firestore database ID. If not specified, the default database '(default)' will be used. | String | ||
Autowired The Firestore client to use for operations. | Firestore | ||
The Google Cloud project ID. If not specified, it will be determined from the service account key or environment. | String | ||
The Service account key that can be used as credentials for the Firestore client. It can be loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | String | ||
When true, the consumer will listen for real-time updates on the collection. | false | boolean | |
If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | false | boolean | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | PollingConsumerPollStrategy | ||
The document ID to use for document-specific operations. | String | ||
Set the operation for the producer. Enum values:
| GoogleFirestoreOperations | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | ||
The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | int | ||
To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | int | ||
Milliseconds before the next poll. | 500 | long | |
If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean | |
Milliseconds before the first poll starts. | 1000 | long | |
Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long | |
The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. Enum values:
| TRACE | LoggingLevel | |
Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | ScheduledExecutorService | ||
To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object | |
To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. This is a multi-value option with prefix: scheduler. | Map | ||
Whether the scheduler should be auto started. | true | boolean | |
Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit | |
Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean |
Message Headers
The Google Firestore component supports 16 message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelGoogleFirestoreOperation (producer) Constant: | The operation to perform. Enum values:
| GoogleFirestoreOperations | |
CamelGoogleFirestoreCollectionName (producer) Constant: | The collection name to use for the operation. | String | |
CamelGoogleFirestoreDocumentId (producer) Constant: | The document ID to use for the operation. | String | |
CamelGoogleFirestoreQueryField (producer) Constant: | The field name for query filtering. | String | |
CamelGoogleFirestoreQueryOperator (producer) Constant: | The operator for query filtering (e.g., ==, , =, !=, array-contains, in, array-contains-any, not-in). | String | |
CamelGoogleFirestoreQueryValue (producer) Constant: | The value for query filtering. | Object | |
CamelGoogleFirestoreQueryLimit (producer) Constant: | The maximum number of documents to return in a query. | Integer | |
CamelGoogleFirestoreQueryOrderBy (producer) Constant: | The field to order the query results by. | String | |
CamelGoogleFirestoreQueryOrderDirection (producer) Constant: | The direction to order the query results (ASCENDING or DESCENDING). Enum values:
| Query$Direction | |
CamelGoogleFirestoreResponseDocumentId (consumer) Constant: | The document ID from the response. | String | |
CamelGoogleFirestoreResponseDocumentPath (consumer) Constant: | The document path from the response. | String | |
CamelGoogleFirestoreResponseCreateTime (consumer) Constant: | The document create time. | Timestamp | |
CamelGoogleFirestoreResponseUpdateTime (consumer) Constant: | The document update time. | Timestamp | |
CamelGoogleFirestoreResponseReadTime (consumer) Constant: | The document read time. | Timestamp | |
CamelGoogleFirestoreMerge (producer) Constant: | When true, merge the data with existing document data instead of overwriting. | false | Boolean |
CamelGoogleFirestoreMergeFields (producer) Constant: | List of field paths to merge when using merge option. | List |
Usage
Google Firestore Producer Operations
Google Firestore component provides the following operations on the producer side:
-
setDocument- Create or overwrite a document with a specific ID -
createDocument- Create a new document with an auto-generated ID -
getDocumentById- Retrieve a document by its ID -
updateDocument- Update specific fields of a document -
deleteDocument- Delete a document -
queryCollection- Query documents with filters -
listDocuments- List all documents in a collection -
listCollections- List all collections
If you don’t specify an operation explicitly, the producer will perform a setDocument operation.
Supported Input Formats
For operations that require document data (setDocument, createDocument, updateDocument), the component accepts the following input formats:
-
Map<String, Object> - Java Map with field names as keys
-
JSON String - A valid JSON object string (e.g.,
{"name": "John", "age": 30}) -
Any object - Convertible to Map via Camel’s type converter
JSON String Example:
// Using JSON string as input
String json = """
{
"name": "John Doe",
"email": "john@example.com",
"age": 30,
"active": true
}
""";
from("direct:start")
.setBody(constant(json))
.setHeader("CamelGoogleFirestoreDocumentId", constant("user123"))
.to("google-firestore://users?operation=setDocument"); Google Firestore Consumer
The consumer can poll documents from a collection or listen for real-time updates.
-
Polling mode (default): Periodically polls the collection for all documents
-
Real-time mode: Listens for document changes using Firestore’s real-time listeners
To enable real-time updates:
from("google-firestore://myCollection?realtimeUpdates=true")
.to("log:changes"); Advanced Component Configuration
If you need more control over the Firestore client instance configuration, you can create your own instance and refer to it in your Camel google-firestore component configuration:
from("google-firestore://myCollection?firestoreClient=#myFirestoreClient")
.to("mock:result"); Producer Operation Examples
Create Document with Auto-Generated ID
This operation creates a new document with an auto-generated unique ID:
Map<String, Object> document = new HashMap<>();
document.put("name", "John Doe");
document.put("email", "john@example.com");
document.put("age", 30);
from("direct:start")
.setBody(constant(document))
.to("google-firestore://users?operation=createDocument")
.log("Created document with ID: ${header.CamelGoogleFirestoreResponseDocumentId}"); Set Document with Specific ID
This operation creates or overwrites a document with a specific ID:
Map<String, Object> document = new HashMap<>();
document.put("name", "Jane Doe");
document.put("email", "jane@example.com");
from("direct:start")
.setBody(constant(document))
.setHeader("CamelGoogleFirestoreDocumentId", constant("user123"))
.to("google-firestore://users?operation=setDocument")
.log("Document saved"); Set Document with Merge
To merge data with an existing document instead of overwriting:
Map<String, Object> updates = new HashMap<>();
updates.put("lastLogin", new Date());
from("direct:start")
.setBody(constant(updates))
.setHeader("CamelGoogleFirestoreDocumentId", constant("user123"))
.setHeader("CamelGoogleFirestoreMerge", constant(true))
.to("google-firestore://users?operation=setDocument")
.log("Document merged"); Get Document by ID
This operation retrieves a document by its ID:
from("direct:start")
.setHeader("CamelGoogleFirestoreDocumentId", constant("user123"))
.to("google-firestore://users?operation=getDocumentById")
.log("Document data: ${body}"); The response body will contain a Map<String, Object> with the document data, or null if the document doesn’t exist.
Update Document
This operation updates specific fields without overwriting the entire document:
Map<String, Object> updates = new HashMap<>();
updates.put("status", "active");
updates.put("updatedAt", new Date());
from("direct:start")
.setBody(constant(updates))
.setHeader("CamelGoogleFirestoreDocumentId", constant("user123"))
.to("google-firestore://users?operation=updateDocument")
.log("Document updated"); Delete Document
This operation deletes a document:
from("direct:start")
.setHeader("CamelGoogleFirestoreDocumentId", constant("user123"))
.to("google-firestore://users?operation=deleteDocument")
.log("Document deleted: ${body}"); List Documents
This operation lists all documents in a collection:
from("direct:start")
.to("google-firestore://users?operation=listDocuments")
.log("Found ${body.size()} documents"); The response body will contain a List<Map<String, Object>> with each document’s data. Each document includes _id and _path fields with the document ID and path.
Query Collection
This operation queries documents with filters:
from("direct:start")
.setHeader("CamelGoogleFirestoreQueryField", constant("age"))
.setHeader("CamelGoogleFirestoreQueryOperator", constant(">="))
.setHeader("CamelGoogleFirestoreQueryValue", constant(21))
.setHeader("CamelGoogleFirestoreQueryLimit", constant(10))
.setHeader("CamelGoogleFirestoreQueryOrderBy", constant("age"))
.to("google-firestore://users?operation=queryCollection")
.log("Found ${body.size()} matching documents"); Supported query operators:
-
==oreq- Equal to -
!=orne- Not equal to -
<orlt- Less than -
⇐orlte- Less than or equal to -
>orgt- Greater than -
>=orgte- Greater than or equal to -
array-contains- Array contains value -
in- Value in list -
array-contains-any- Array contains any value in list -
not-in- Value not in list
List Collections
This operation lists all collections in the database:
from("direct:start")
.to("google-firestore://anyCollection?operation=listCollections")
.log("Collections: ${body}"); To list subcollections under a specific document:
from("direct:start")
.setHeader("CamelGoogleFirestoreDocumentId", constant("user123"))
.to("google-firestore://users?operation=listCollections")
.log("Subcollections: ${body}"); Consumer Examples
Poll Documents
Poll all documents from a collection every 30 seconds:
from("google-firestore://users?delay=30000")
.log("Document ID: ${header.CamelGoogleFirestoreResponseDocumentId}")
.log("Document data: ${body}")
.to("mock:result"); Real-time Updates
Listen for document changes in real-time:
from("google-firestore://users?realtimeUpdates=true")
.log("Change type: ${header.CamelGoogleFirestoreChangeType}")
.log("Document ID: ${header.CamelGoogleFirestoreResponseDocumentId}")
.log("Document data: ${body}")
.to("mock:result"); The CamelGoogleFirestoreChangeType header indicates the type of change: ADDED, MODIFIED, or REMOVED.
Data Types
Input Data Formats
For write operations (setDocument, createDocument, updateDocument), the component accepts the following input formats in the message body:
| Format | Description | Example |
|---|---|---|
| Java Map with field names as keys |
|
JSON String | Valid JSON object string |
|
POJO | Any object convertible to Map via Camel’s type converter | Custom Java beans |
JSON String Input
You can send a JSON string directly as the message body. The component will automatically parse it:
// Simple JSON
from("direct:start")
.setBody(constant("{\"name\": \"John\", \"age\": 30}"))
.setHeader("CamelGoogleFirestoreDocumentId", constant("user123"))
.to("google-firestore://users?operation=setDocument");
// Multi-line JSON with text blocks (Java 15+)
String json = """
{
"name": "John Doe",
"email": "john@example.com",
"age": 30,
"active": true,
"tags": ["admin", "user"],
"address": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
}
}
""";
from("direct:start")
.setBody(constant(json))
.to("google-firestore://users?operation=createDocument"); Supported Firestore Data Types
The following Java types are automatically converted to Firestore data types:
| Java Type | Firestore Type | Notes |
|---|---|---|
| String | Text data |
| Integer | 64-bit signed integer |
| Floating-point | 64-bit double precision |
| Boolean |
|
| Timestamp | Converted to Firestore Timestamp |
| Timestamp | Native Firestore Timestamp |
| Array | Ordered list, nested types supported |
| Map | Nested document/object |
| Null | Null value |
| Bytes | Binary data (max 1MB) |
| GeoPoint | Latitude/longitude coordinates |
| Reference | Reference to another document |
Output Data Formats
Single Document Operations
For getDocumentById, the response body is:
-
Map<String, Object>- Document data if found -
null- If document does not exist
List/Query Operations
For listDocuments and queryCollection, the response body is:
-
List<Map<String, Object>>- List of documents
Each document Map includes additional metadata fields:
-
_id- The document ID -
_path- The full document path (e.g.,users/user123)
Message Headers
The component uses the following headers:
Producer Headers (Input)
| Header | Type | Description |
|---|---|---|
|
| The operation to perform |
|
| Override the collection name |
|
| The document ID for document operations |
|
| Field name for query filtering |
|
| Operator for query filtering |
|
| Value for query filtering |
|
| Maximum documents to return |
|
| Field to order results by |
|
| Order direction (ASCENDING/DESCENDING) |
|
| Merge data with existing document |
|
| Specific fields to merge |
Consumer/Response Headers (Output)
| Header | Type | Description |
|---|---|---|
|
| The document ID |
|
| The full document path |
|
| Document creation time |
|
| Document last update time |
|
| Document read time |
|
| Change type for real-time updates (ADDED, MODIFIED, REMOVED) |
Spring Boot Auto-Configuration
When using google-firestore with Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-google-firestore-starter</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> The component supports 14 options, which are listed below.