Azure CosmosDB
Since Camel 3.10
Both producer and consumer are supported
Azure Cosmos DB is Microsoft’s globally distributed, multimodel database service for operational and analytics workloads. It offers multi-mastering feature by automatically scaling throughput, compute, and storage. This component interacts with Azure CosmosDB through Azure SQL API.
Prerequisites
You must have a valid Azure Cosmos DB account. More information is available at Azure Documentation Portal.
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-azure-cosmosdb</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI Format
azure-cosmosdb://[databaseName][/containerName][?options] In case of the consumer, databaseName, containerName are required, In case of the producer, it depends on the operation that being requested, for example if operation is on a database level, e.b: deleteDatabase, only databaseName is required, but in case of operation being requested in container level, e.g: readItem, then databaseName and containerName are required.
You can append query options to the URI in the following format, ?options=value&option2=value&…
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 Azure CosmosDB component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Deprecated Whether to enable client telemetry. Deprecation note: Has no effect: the azure-cosmos SDK ignores this flag, as it can no longer send client telemetry to the service. | false | boolean | |
The configuration of the component. Each endpoint that the component creates starts from a copy of it, to which the options of the endpoint are applied. | CosmosDbConfiguration | ||
Whether the client shares its connections in Direct mode with the other clients of the JVM that enable this option, such as the clients of other endpoints or of other accounts. The connection settings of the first of these clients, such as its timeouts, then apply to all of them. | false | boolean | |
The default consistency level of the requests of the client. It must be the same as or weaker than the default consistency level of the account. From the strongest to the weakest: Strong, BoundedStaleness, Session, ConsistentPrefix and Eventual. Enum values:
| Session | ConsistencyLevel | |
The partition key path of a container that the component creates, for example /myPartitionKey. A / is added in front when it is missing. Required by createContainer and when createContainerIfNotExists is true, and the CamelAzureCosmosDbContainerPartitionKeyPath header replaces it for the producer. | String | ||
Whether Cosmos DB returns the item in the response of createItem, upsertItem and replaceItem, which the producer then sets as the body. If false, the body is null after these operations, which saves network traffic. The consumer requires true: its change feed processor fails to start with false. | true | boolean | |
Autowired To use a custom com.azure.cosmos.CosmosAsyncClient for all requests. When this option is set or autowired, the databaseEndpoint, accountKey, credentialType, consistencyLevel, preferredRegions, clientTelemetryEnabled, connectionSharingAcrossClientsEnabled, multipleWriteRegionsEnabled, readRequestsFallbackEnabled and contentResponseOnWriteEnabled options are not used. The endpoint does not close a client that is set or autowired. | CosmosAsyncClient | ||
Whether to create the container when it does not exist, with the containerPartitionKeyPath and throughputProperties options, and the indexingPolicy option for the producer. The consumer creates it when it starts, and the producer before replaceContainerThroughput and each operation on items except deleteItem. The CamelAzureCosmosDbCreateContainerIfNotExist header replaces it for the producer. | false | boolean | |
Whether to create the database when it does not exist, with the throughputProperties option. The consumer creates it when it starts, and the producer before each operation on the database, its containers or their items, except deleteDatabase and deleteContainer. The CamelAzureCosmosDbCreateDatabaseIfNotExist header replaces it for the producer. | false | boolean | |
The URI of the Azure Cosmos DB account, for example https://myaccount.documents.azure.com:443/. Required unless the cosmosAsyncClient option is set, which replaces it. | String | ||
Whether the client sends writes to any writable region of a geo-replicated account, in the order of preferredRegions. Has no effect unless multi-region writes are enabled on the account. | true | boolean | |
A comma-separated list of the preferred regions of a geo-replicated account, in order of preference, for example East US,West US. The client sends its requests to the first available region of this list. | String | ||
Whether the client can send reads to the other regions of the account, for example when a region is not available. Has no effect unless the account has more than one region. | true | boolean | |
The throughput, as a com.azure.cosmos.models.ThroughputProperties, for createDatabase, createContainer, replaceDatabaseThroughput and replaceContainerThroughput, and for the databases and containers that the create*IfNotExists options create, the lease database and lease container included. The CamelAzureCosmosDbThroughputProperties header replaces it for the producer. | ThroughputProperties | ||
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 | |
The com.azure.cosmos.models.ChangeFeedProcessorOptions of the change feed processor, for example to start from the beginning of the change feed or from a point in time. If not set, the defaults of the SDK apply: at most 100 items per batch, a lease renew interval of 17 seconds, a lease acquire interval of 13 seconds, a lease expiration interval of 60 seconds, a feed poll delay of 5 seconds, no maximum scale count, and only the changes after the first start. | ChangeFeedProcessorOptions | ||
Whether the consumer creates the lease container when it does not exist, with the partition key path /id and the throughputProperties option. | false | boolean | |
Whether the consumer creates the lease database when it does not exist, with the throughputProperties option. | false | boolean | |
The name of the host, which identifies this consumer in the leases of the change feed processor. The consumers that share a lease container need different names. If not set, a random name is generated each time the change feed processor is built. | String | ||
The name of the lease container, where the change feed processor of the consumer stores how far it has processed each range of the feed and which host processes it. The consumers that use the same lease container for the same container share the work of processing its changes. The lease container must have the partition key path /id. | camel-lease | String | |
The name of the database of the lease container. If not set, the database of the databaseName option is used. | String | ||
The id of the item for readItem, replaceItem and deleteItem. The CamelAzureCosmosDbItemId header replaces it. | String | ||
The value of the partition key of the item, as a String, for createItem, upsertItem, replaceItem, deleteItem and readItem, and of the items that readAllItems reads. If not set, the partition key value is null. The CamelAzureCosmosDbItemPartitionKey header replaces it. | 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 | |
The operation that the producer performs. The operations on a database use databaseName, and the operations on a container or its items also use containerName. The CamelAzureCosmosDbOperation header replaces this option. Enum values:
| listDatabases | CosmosDbOperationsDefinition | |
The SQL query of queryDatabases, queryContainers and queryItems, for example SELECT * FROM c WHERE c.id = '1'. The CamelAzureCosmosDbQuery header replaces it. | String | ||
The com.azure.cosmos.models.CosmosQueryRequestOptions of queryDatabases, listContainers, queryContainers, readAllItems and queryItems, for example to set the maximum number of items per page. The CamelAzureCosmosDbQueryRequestOptions header replaces it. | CosmosQueryRequestOptions | ||
The com.azure.cosmos.models.IndexingPolicy of a container that the producer creates, with createContainer or because createContainerIfNotExists is true. If not set, the container gets the default indexing policy of Cosmos DB. The CamelAzureCosmosDbIndexingPolicy header replaces it, and the consumer does not use it. | IndexingPolicy | ||
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 | |
The key of the Azure Cosmos DB account, a read-write key or a read-only key, that authorizes the requests when credentialType is SHARED_ACCOUNT_KEY. Not used when the cosmosAsyncClient option is set. | String | ||
How the client authenticates. SHARED_ACCOUNT_KEY: with the accountKey option. AZURE_IDENTITY: with a DefaultAzureCredential of the Azure Identity library, which finds the credentials in the environment, such as environment variables, a managed identity or the Azure CLI. Not used when the cosmosAsyncClient option is set. Enum values:
| SHARED_ACCOUNT_KEY | CredentialType |
Endpoint Options
The Azure CosmosDB endpoint is configured using URI syntax:
azure-cosmosdb:databaseName/containerName
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The name of the database. The consumer requires it. The producer uses it for each operation except listDatabases and queryDatabases, and the CamelAzureCosmosDbDatabaseName header replaces it. | String | ||
The name of the container. The consumer requires it, and receives the changes of this container. The producer uses it for the operations on a container and on its items, and the CamelAzureCosmosDbContainerName header replaces it. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Deprecated Whether to enable client telemetry. Deprecation note: Has no effect: the azure-cosmos SDK ignores this flag, as it can no longer send client telemetry to the service. | false | boolean | |
Whether the client shares its connections in Direct mode with the other clients of the JVM that enable this option, such as the clients of other endpoints or of other accounts. The connection settings of the first of these clients, such as its timeouts, then apply to all of them. | false | boolean | |
The default consistency level of the requests of the client. It must be the same as or weaker than the default consistency level of the account. From the strongest to the weakest: Strong, BoundedStaleness, Session, ConsistentPrefix and Eventual. Enum values:
| Session | ConsistencyLevel | |
The partition key path of a container that the component creates, for example /myPartitionKey. A / is added in front when it is missing. Required by createContainer and when createContainerIfNotExists is true, and the CamelAzureCosmosDbContainerPartitionKeyPath header replaces it for the producer. | String | ||
Whether Cosmos DB returns the item in the response of createItem, upsertItem and replaceItem, which the producer then sets as the body. If false, the body is null after these operations, which saves network traffic. The consumer requires true: its change feed processor fails to start with false. | true | boolean | |
Autowired To use a custom com.azure.cosmos.CosmosAsyncClient for all requests. When this option is set or autowired, the databaseEndpoint, accountKey, credentialType, consistencyLevel, preferredRegions, clientTelemetryEnabled, connectionSharingAcrossClientsEnabled, multipleWriteRegionsEnabled, readRequestsFallbackEnabled and contentResponseOnWriteEnabled options are not used. The endpoint does not close a client that is set or autowired. | CosmosAsyncClient | ||
Whether to create the container when it does not exist, with the containerPartitionKeyPath and throughputProperties options, and the indexingPolicy option for the producer. The consumer creates it when it starts, and the producer before replaceContainerThroughput and each operation on items except deleteItem. The CamelAzureCosmosDbCreateContainerIfNotExist header replaces it for the producer. | false | boolean | |
Whether to create the database when it does not exist, with the throughputProperties option. The consumer creates it when it starts, and the producer before each operation on the database, its containers or their items, except deleteDatabase and deleteContainer. The CamelAzureCosmosDbCreateDatabaseIfNotExist header replaces it for the producer. | false | boolean | |
The URI of the Azure Cosmos DB account, for example https://myaccount.documents.azure.com:443/. Required unless the cosmosAsyncClient option is set, which replaces it. | String | ||
Whether the client sends writes to any writable region of a geo-replicated account, in the order of preferredRegions. Has no effect unless multi-region writes are enabled on the account. | true | boolean | |
A comma-separated list of the preferred regions of a geo-replicated account, in order of preference, for example East US,West US. The client sends its requests to the first available region of this list. | String | ||
Whether the client can send reads to the other regions of the account, for example when a region is not available. Has no effect unless the account has more than one region. | true | boolean | |
The throughput, as a com.azure.cosmos.models.ThroughputProperties, for createDatabase, createContainer, replaceDatabaseThroughput and replaceContainerThroughput, and for the databases and containers that the create*IfNotExists options create, the lease database and lease container included. The CamelAzureCosmosDbThroughputProperties header replaces it for the producer. | ThroughputProperties | ||
The com.azure.cosmos.models.ChangeFeedProcessorOptions of the change feed processor, for example to start from the beginning of the change feed or from a point in time. If not set, the defaults of the SDK apply: at most 100 items per batch, a lease renew interval of 17 seconds, a lease acquire interval of 13 seconds, a lease expiration interval of 60 seconds, a feed poll delay of 5 seconds, no maximum scale count, and only the changes after the first start. | ChangeFeedProcessorOptions | ||
Whether the consumer creates the lease container when it does not exist, with the partition key path /id and the throughputProperties option. | false | boolean | |
Whether the consumer creates the lease database when it does not exist, with the throughputProperties option. | false | boolean | |
The name of the host, which identifies this consumer in the leases of the change feed processor. The consumers that share a lease container need different names. If not set, a random name is generated each time the change feed processor is built. | String | ||
The name of the lease container, where the change feed processor of the consumer stores how far it has processed each range of the feed and which host processes it. The consumers that use the same lease container for the same container share the work of processing its changes. The lease container must have the partition key path /id. | camel-lease | String | |
The name of the database of the lease container. If not set, the database of the databaseName option is used. | 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 | |
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 | ||
The id of the item for readItem, replaceItem and deleteItem. The CamelAzureCosmosDbItemId header replaces it. | String | ||
The value of the partition key of the item, as a String, for createItem, upsertItem, replaceItem, deleteItem and readItem, and of the items that readAllItems reads. If not set, the partition key value is null. The CamelAzureCosmosDbItemPartitionKey header replaces it. | String | ||
The operation that the producer performs. The operations on a database use databaseName, and the operations on a container or its items also use containerName. The CamelAzureCosmosDbOperation header replaces this option. Enum values:
| listDatabases | CosmosDbOperationsDefinition | |
The SQL query of queryDatabases, queryContainers and queryItems, for example SELECT * FROM c WHERE c.id = '1'. The CamelAzureCosmosDbQuery header replaces it. | String | ||
The com.azure.cosmos.models.CosmosQueryRequestOptions of queryDatabases, listContainers, queryContainers, readAllItems and queryItems, for example to set the maximum number of items per page. The CamelAzureCosmosDbQueryRequestOptions header replaces it. | CosmosQueryRequestOptions | ||
The com.azure.cosmos.models.IndexingPolicy of a container that the producer creates, with createContainer or because createContainerIfNotExists is true. If not set, the container gets the default indexing policy of Cosmos DB. The CamelAzureCosmosDbIndexingPolicy header replaces it, and the consumer does not use it. | IndexingPolicy | ||
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 key of the Azure Cosmos DB account, a read-write key or a read-only key, that authorizes the requests when credentialType is SHARED_ACCOUNT_KEY. Not used when the cosmosAsyncClient option is set. | String | ||
How the client authenticates. SHARED_ACCOUNT_KEY: with the accountKey option. AZURE_IDENTITY: with a DefaultAzureCredential of the Azure Identity library, which finds the credentials in the environment, such as environment variables, a managed identity or the Azure CLI. Not used when the cosmosAsyncClient option is set. Enum values:
| SHARED_ACCOUNT_KEY | CredentialType |
Message Headers
The Azure CosmosDB component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelAzureCosmosDbDatabaseName (producer) Constant: | The name of the database. Replaces the databaseName option. | String | |
CamelAzureCosmosDbContainerName (producer) Constant: | The name of the container. Replaces the containerName option. | String | |
CamelAzureCosmosDbOperation (producer) Constant: | The operation that the producer performs. Replaces the operation option. Enum values:
| CosmosDbOperationsDefinition | |
CamelAzureCosmosDbQuery (producer) Constant: | The SQL query of queryDatabases, queryContainers and queryItems. Replaces the query option. | String | |
CamelAzureCosmosDbQueryRequestOptions (producer) Constant: | The options of queryDatabases, listContainers, queryContainers, readAllItems and queryItems. Replaces the queryRequestOptions option. | CosmosQueryRequestOptions | |
CamelAzureCosmosDbCreateDatabaseIfNotExist (producer) Constant: | Whether to create the database when it does not exist. Replaces the createDatabaseIfNotExists option. | Boolean | |
CamelAzureCosmosDbCreateContainerIfNotExist (producer) Constant: | Whether to create the container when it does not exist. Replaces the createContainerIfNotExists option. | Boolean | |
CamelAzureCosmosDbIndexingPolicy (producer) Constant: | The indexing policy of a container that the producer creates. Replaces the indexingPolicy option. | IndexingPolicy | |
CamelAzureCosmosDbThroughputProperties (producer) Constant: | The throughput of a database or container that the producer creates, and the new throughput of replaceDatabaseThroughput and replaceContainerThroughput. Replaces the throughputProperties option. | ThroughputProperties | |
CamelAzureCosmosDbDatabaseRequestOptions (producer) Constant: | The request options of deleteDatabase. | CosmosDatabaseRequestOptions | |
CamelAzureCosmosDbContainerPartitionKeyPath (producer) Constant: | The partition key path of a container that the producer creates. Replaces the containerPartitionKeyPath option. | String | |
CamelAzureCosmosDbContainerRequestOptions (producer) Constant: | The request options of deleteContainer. | CosmosContainerRequestOptions | |
CamelAzureCosmosDbItemPartitionKey (producer) Constant: | The value of the partition key of the item for createItem, upsertItem, replaceItem, deleteItem and readItem, and of the items that readAllItems reads. Replaces the itemPartitionKey option. A com.azure.cosmos.models.PartitionKey is used as it is, for example for a partition key value that is a number or a boolean; any other value is converted to a String. | PartitionKey | |
CamelAzureCosmosDbItemRequestOptions (producer) Constant: | The request options of createItem, upsertItem, replaceItem, deleteItem and readItem. | CosmosItemRequestOptions | |
CamelAzureCosmosDbItemId (producer) Constant: | The id of the item for readItem, replaceItem and deleteItem. Replaces the itemId option. | String | |
CamelAzureCosmosDbResourceId (producer) Constant: | The resource id of the database or container, set by the operations on a database or a container that get its properties back, such as createDatabase and createContainer. | String | |
CamelAzureCosmosDbEtag (producer) Constant: | The entity tag of the database, container, throughput or item that the operation returns. | String | |
CamelAzureCosmosDbTimestamp (producer) Constant: | The time of the last update of the database, container or throughput that the operation returns. | Instant | |
CamelAzureCosmosDbResponseHeaders (producer) Constant: | The headers of the response of Cosmos DB, for all operations except listDatabases, queryDatabases, listContainers, queryContainers, readAllItems and queryItems. | Map | |
CamelAzureCosmosDbStatusCode (producer) Constant: | The HTTP status code of the response of Cosmos DB, for all operations except listDatabases, queryDatabases, listContainers, queryContainers, readAllItems and queryItems. | Integer | |
CamelAzureCosmosDbDefaultTimeToLiveInSeconds (producer) Constant: | The default time to live of the items of the container, in seconds, set by the operations on a container that get its properties back, such as createContainer. | Integer | |
CamelAzureCosmosDbManualThroughput (producer) Constant: | The manual throughput, in request units per second, after replaceDatabaseThroughput or replaceContainerThroughput. | Integer | |
CamelAzureCosmosDbAutoscaleMaxThroughput (producer) Constant: | The maximum autoscale throughput, in request units per second, after replaceDatabaseThroughput or replaceContainerThroughput. | Integer |
Message Body
The message body at each side of the Azure CosmosDB component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The items of one batch of the change feed: a List with a Map per item created or changed, with the system fields of Cosmos DB such as _etag and _lsn. |
Producer input |
| The item for createItem, upsertItem and replaceItem: a Map or a POJO, which Jackson serializes, or the JSON of the item as text, bytes, a stream or a file, which is parsed into a Map. These operations write one item: a List, or JSON that is not an object, fails. The other operations do not use the body: the item id, the partition key and the query are options or headers.
|
Producer output |
| A List of the properties of the SDK for listDatabases, the default, and the list and query operations of databases and containers; the item as written for createItem, upsertItem and replaceItem, as a Map for a Map or JSON body and of the class of the POJO for a POJO, or no body with contentResponseOnWriteEnabled=false; the item as a Map for readItem, and a List of them for readAllItems and queryItems, whose elements are values for a SELECT VALUE query. The operations on databases, containers and throughput leave the body and set the response in headers.
Not known when |
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Usage
Authentication Information
To use this component, you have two options to provide the required Azure authentication information:
-
Provide
accountKeyanddatabaseEndpointfor your Azure CosmosDB account. The account key can be generated through your CosmosDB Azure portal. -
Provide a CosmosAsyncClient instance which can be provided into
cosmosAsyncClient.
Async Consumer and Producer
This component implements the async Consumer and producer.
This allows camel route to consume and produce events asynchronously without blocking any threads.
Consumer health check
When Cosmos DB cannot be reached yet, the lease container does not exist yet or a role assignment has not propagated yet, the change feed processor of a consumer cannot start. The consumer then tries to start it again, with a backoff of 1 to 30 seconds, until it starts or the consumer stops, and meanwhile the route and the consumer are started. With the consumer health checks of Camel enabled, the readiness check of the consumer of the route (consumer:<routeId>) is the initial state of the health checks (camel.health.initial-state, DOWN by default) while the first attempt runs, DOWN with the failure of the last attempt and the number of failed attempts (failed.starts) while it cannot start, and UP once it has started. It does not follow what the change feed processor does after it started. As for any consumer check, camel-health asks it only for a route that starts with the CamelContext, and camel.health.exclude-pattern=consumer:<routeId> leaves it out.
Azure CosmosDB Producer operations
Camel Azure CosmosDB component provides a wide range of operations on the producer side:
Operations on the service level
For these operations, databaseName is required except for queryDatabases and listDatabases operations.
| Operation | Description |
|---|---|
| Gets a list of all databases as |
| Create a database in the specified Azure CosmosDB account. |
|
|
Operations on the database level
For these operations, databaseName is required for all operations here and containerName only for createContainer and queryContainers.
| Operation | Description |
|---|---|
| Delete a database from the Azure CosmosDB account. |
| Create a container in the specified Azure CosmosDB database. |
| Replace the throughput for the specified Azure CosmosDB database. |
| Gets a list of all containers in the specified database as |
|
|
Operations on the container level
For these operations, databaseName and containerName is required for all operations here.
| Operation | Description |
|---|---|
| Delete a container from the specified Azure CosmosDB database. |
| Replace the throughput for the specified Azure CosmosDB container. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The message body of createItem, upsertItem and replaceItem is one item: a POJO or a Map<String, ?>, which the Azure SDK serializes with Jackson, or the JSON of the item as a String, a byte[], a stream or a file (such as the body of the file consumer), which the component parses into a Map first. After the operation, the message body is the item as written by Cosmos DB, with its system fields such as _etag: a Map for a Map or JSON body, and the class of the POJO for a POJO. With contentResponseOnWriteEnabled=false there is no message body.
A byte[], an InputStream or a file is read as bytes, in which Jackson detects JSON in UTF-8, UTF-16 or UTF-32. For JSON in another charset, such as a file that the file consumer reads with charset=ISO-8859-1, convert the body to a String first, for example with convertBodyTo(String.class), which reads the file with its charset.
These operations write one item: a List body, or JSON that is not an object (such as a JSON array), fails with an IllegalArgumentException. To write several items, send each item in its own exchange, for example with the Split EIP.
Refer to the example section in this page to learn how to use these operations into your camel application.
Examples
Consuming records from a specific container
For example, to consume records from a specific container in a specific database to a file, use the following snippet. The consumer gives a List of the changed items as Map, so marshal it to JSON before writing it:
-
Java
-
XML
-
YAML
from("azure-cosmosdb://camelDb/myContainer?accountKey=MyaccountKey&databaseEndpoint=https//myazure.com:443&leaseDatabaseName=myLeaseDB&createLeaseDatabaseIfNotExists=true&createLeaseContainerIfNotExists=true")
.marshal().json()
.to("file://directory"); <route>
<from uri="azure-cosmosdb://camelDb/myContainer?accountKey=MyaccountKey&databaseEndpoint=https//myazure.com:443&leaseDatabaseName=myLeaseDB&createLeaseDatabaseIfNotExists=true&createLeaseContainerIfNotExists=true"/>
<marshal><json/></marshal>
<to uri="file://directory"/>
</route> - route:
from:
uri: azure-cosmosdb://camelDb/myContainer
parameters:
accountKey: MyaccountKey
databaseEndpoint: "https//myazure.com:443"
leaseDatabaseName: myLeaseDB
createLeaseDatabaseIfNotExists: true
createLeaseContainerIfNotExists: true
steps:
- marshal:
json: {}
- to:
uri: file://directory Operations
-
listDatabases:
-
Java
-
XML
-
YAML
from("direct:start")
.to("azure-cosmosdb://?operation=listDatabases")
.to("mock:result"); <route>
<from uri="direct:start"/>
<to uri="azure-cosmosdb://?operation=listDatabases"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: azure-cosmosdb://
parameters:
operation: listDatabases
- to:
uri: mock:result -
createDatabase:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelAzureCosmosDbDatabaseName", constant("myDb"))
.to("azure-cosmosdb://?operation=createDatabase")
.to("mock:result"); <route>
<from uri="direct:start"/>
<setHeader name="CamelAzureCosmosDbDatabaseName">
<constant>myDb</constant>
</setHeader>
<to uri="azure-cosmosdb://?operation=createDatabase"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelAzureCosmosDbDatabaseName
constant: myDb
- to:
uri: azure-cosmosdb://
parameters:
operation: createDatabase
- to:
uri: mock:result -
deleteDatabase:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelAzureCosmosDbDatabaseName", constant("myDb"))
.to("azure-cosmosdb://?operation=deleteDatabase")
.to("mock:result"); <route>
<from uri="direct:start"/>
<setHeader name="CamelAzureCosmosDbDatabaseName">
<constant>myDb</constant>
</setHeader>
<to uri="azure-cosmosdb://?operation=deleteDatabase"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelAzureCosmosDbDatabaseName
constant: myDb
- to:
uri: azure-cosmosdb://
parameters:
operation: deleteDatabase
- to:
uri: mock:result -
createContainer:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelAzureCosmosDbDatabaseName", constant("databaseName"))
.setHeader("CamelAzureCosmosDbContainerName", constant("containerName"))
.setHeader("CamelAzureCosmosDbContainerPartitionKeyPath", constant("path"))
.setHeader("CamelAzureCosmosDbCreateDatabaseIfNotExist", constant(true))
.to("azure-cosmosdb://?operation=createContainer")
.to("mock:result"); <route>
<from uri="direct:start"/>
<setHeader name="CamelAzureCosmosDbDatabaseName">
<constant>databaseName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbContainerName">
<constant>containerName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbContainerPartitionKeyPath">
<constant>path</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbCreateDatabaseIfNotExist">
<constant>true</constant>
</setHeader>
<to uri="azure-cosmosdb://?operation=createContainer"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelAzureCosmosDbDatabaseName
constant: databaseName
- setHeader:
name: CamelAzureCosmosDbContainerName
constant: containerName
- setHeader:
name: CamelAzureCosmosDbContainerPartitionKeyPath
constant: path
- setHeader:
name: CamelAzureCosmosDbCreateDatabaseIfNotExist
constant: true
- to:
uri: azure-cosmosdb://
parameters:
operation: createContainer
- to:
uri: mock:result -
deleteContainer:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelAzureCosmosDbDatabaseName", constant("databaseName"))
.setHeader("CamelAzureCosmosDbContainerName", constant("containerName"))
.to("azure-cosmosdb://?operation=deleteContainer")
.to("mock:result"); <route>
<from uri="direct:start"/>
<setHeader name="CamelAzureCosmosDbDatabaseName">
<constant>databaseName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbContainerName">
<constant>containerName</constant>
</setHeader>
<to uri="azure-cosmosdb://?operation=deleteContainer"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelAzureCosmosDbDatabaseName
constant: databaseName
- setHeader:
name: CamelAzureCosmosDbContainerName
constant: containerName
- to:
uri: azure-cosmosdb://
parameters:
operation: deleteContainer
- to:
uri: mock:result -
replaceDatabaseThroughput:
from("direct:start")
.process(exchange -> {
exchange.getIn().setHeader("CamelAzureCosmosDbDatabaseName", "databaseName");
exchange.getIn().setHeader("CamelAzureCosmosDbThroughputProperties",
ThroughputProperties.createManualThroughput(700));
})
.to("azure-cosmosdb://?operation=replaceDatabaseThroughput")
.to("mock:result"); -
queryContainers:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelAzureCosmosDbDatabaseName", constant("databaseName"))
.setHeader("CamelAzureCosmosDbQuery", constant("SELECT * from c where c.id = 'myAwesomeContainer'"))
.to("azure-cosmosdb://?operation=queryContainers")
.to("mock:result"); <route>
<from uri="direct:start"/>
<setHeader name="CamelAzureCosmosDbDatabaseName">
<constant>databaseName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbQuery">
<constant>SELECT * from c where c.id = 'myAwesomeContainer'</constant>
</setHeader>
<to uri="azure-cosmosdb://?operation=queryContainers"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelAzureCosmosDbDatabaseName
constant: databaseName
- setHeader:
name: CamelAzureCosmosDbQuery
constant: "SELECT * from c where c.id = 'myAwesomeContainer'"
- to:
uri: azure-cosmosdb://
parameters:
operation: queryContainers
- to:
uri: mock:result -
createItem:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelAzureCosmosDbDatabaseName", constant("databaseName"))
.setHeader("CamelAzureCosmosDbContainerName", constant("containerName"))
.setHeader("CamelAzureCosmosDbContainerPartitionKeyPath", constant("partition"))
.setHeader("CamelAzureCosmosDbItemPartitionKey", constant("test-1"))
.setBody(constant("{\"id\":\"test-id-1\",\"partition\":\"test-1\",\"field1\":\"awesome!\"}"))
.to("azure-cosmosdb://?operation=createItem")
.to("mock:result"); <route>
<from uri="direct:start"/>
<setHeader name="CamelAzureCosmosDbDatabaseName">
<constant>databaseName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbContainerName">
<constant>containerName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbContainerPartitionKeyPath">
<constant>partition</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbItemPartitionKey">
<constant>test-1</constant>
</setHeader>
<setBody>
<constant>{"id":"test-id-1","partition":"test-1","field1":"awesome!"}</constant>
</setBody>
<to uri="azure-cosmosdb://?operation=createItem"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelAzureCosmosDbDatabaseName
constant: databaseName
- setHeader:
name: CamelAzureCosmosDbContainerName
constant: containerName
- setHeader:
name: CamelAzureCosmosDbContainerPartitionKeyPath
constant: partition
- setHeader:
name: CamelAzureCosmosDbItemPartitionKey
constant: "test-1"
- setBody:
constant: '{"id":"test-id-1","partition":"test-1","field1":"awesome!"}'
- to:
uri: azure-cosmosdb://
parameters:
operation: createItem
- to:
uri: mock:result -
replaceItem:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelAzureCosmosDbDatabaseName", constant("databaseName"))
.setHeader("CamelAzureCosmosDbContainerName", constant("containerName"))
.setHeader("CamelAzureCosmosDbItemPartitionKey", constant("test-1"))
.setHeader("CamelAzureCosmosDbItemId", constant("test-id-1"))
.setBody(constant("{\"id\":\"test-id-1\",\"partition\":\"test-1\",\"field1\":\"awesome!\"}"))
.to("azure-cosmosdb://?operation=replaceItem")
.to("mock:result"); <route>
<from uri="direct:start"/>
<setHeader name="CamelAzureCosmosDbDatabaseName">
<constant>databaseName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbContainerName">
<constant>containerName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbItemPartitionKey">
<constant>test-1</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbItemId">
<constant>test-id-1</constant>
</setHeader>
<setBody>
<constant>{"id":"test-id-1","partition":"test-1","field1":"awesome!"}</constant>
</setBody>
<to uri="azure-cosmosdb://?operation=replaceItem"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelAzureCosmosDbDatabaseName
constant: databaseName
- setHeader:
name: CamelAzureCosmosDbContainerName
constant: containerName
- setHeader:
name: CamelAzureCosmosDbItemPartitionKey
constant: "test-1"
- setHeader:
name: CamelAzureCosmosDbItemId
constant: "test-id-1"
- setBody:
constant: '{"id":"test-id-1","partition":"test-1","field1":"awesome!"}'
- to:
uri: azure-cosmosdb://
parameters:
operation: replaceItem
- to:
uri: mock:result -
deleteItem:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelAzureCosmosDbDatabaseName", constant("databaseName"))
.setHeader("CamelAzureCosmosDbContainerName", constant("containerName"))
.setHeader("CamelAzureCosmosDbItemPartitionKey", constant("test-1"))
.setHeader("CamelAzureCosmosDbItemId", constant("test-id-1"))
.to("azure-cosmosdb://?operation=deleteItem")
.to("mock:result"); <route>
<from uri="direct:start"/>
<setHeader name="CamelAzureCosmosDbDatabaseName">
<constant>databaseName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbContainerName">
<constant>containerName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbItemPartitionKey">
<constant>test-1</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbItemId">
<constant>test-id-1</constant>
</setHeader>
<to uri="azure-cosmosdb://?operation=deleteItem"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelAzureCosmosDbDatabaseName
constant: databaseName
- setHeader:
name: CamelAzureCosmosDbContainerName
constant: containerName
- setHeader:
name: CamelAzureCosmosDbItemPartitionKey
constant: "test-1"
- setHeader:
name: CamelAzureCosmosDbItemId
constant: "test-id-1"
- to:
uri: azure-cosmosdb://
parameters:
operation: deleteItem
- to:
uri: mock:result -
queryItems:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelAzureCosmosDbDatabaseName", constant("databaseName"))
.setHeader("CamelAzureCosmosDbContainerName", constant("containerName"))
.setHeader("CamelAzureCosmosDbQuery", constant("SELECT c.id,c.field2,c.field1 from c where c.id = 'test-id-1'"))
.to("azure-cosmosdb://?operation=queryItems")
.to("mock:result"); <route>
<from uri="direct:start"/>
<setHeader name="CamelAzureCosmosDbDatabaseName">
<constant>databaseName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbContainerName">
<constant>containerName</constant>
</setHeader>
<setHeader name="CamelAzureCosmosDbQuery">
<constant>SELECT c.id,c.field2,c.field1 from c where c.id = 'test-id-1'</constant>
</setHeader>
<to uri="azure-cosmosdb://?operation=queryItems"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelAzureCosmosDbDatabaseName
constant: databaseName
- setHeader:
name: CamelAzureCosmosDbContainerName
constant: containerName
- setHeader:
name: CamelAzureCosmosDbQuery
constant: "SELECT c.id,c.field2,c.field1 from c where c.id = 'test-id-1'"
- to:
uri: azure-cosmosdb://
parameters:
operation: queryItems
- to:
uri: mock:result Azure CosmosDB Consumer
Camel Azure CosmosDB uses ChangeFeed pattern to capture a feed of events and feed them into the Camel in an Async manner, something similar to the Change Data Capture (CDC) design pattern. However, it doesn’t capture deletions as these are removed from the feed as well.
To use the Camel Azure CosmosDB, containerName and databaseName are required. However, there are more options that need to be set to use this feature:
-
leaseDatabaseName: Sets the lease database where theleaseContainerNamewill be stored. If it is not specified, this component will store the lease container in the same database that is specified in databaseName. It will be auto-created ifcreateLeaseDatabaseIfNotExistsis set to true. -
leaseContainerName: Sets the lease container which acts as a state storage and coordinates processing the change feed across multiple workers. The lease container can be stored in the same account as the monitored container or in a separate account. It will be auto-created ifcreateLeaseContainerIfNotExistsis set to true. If not specified, this component will create container calledcamel-lease. -
hostName: Sets the hostname. The host: a host is an application instance that uses the change feed processor to listen for changes. Multiple instances with the same lease configuration can run in parallel, but each instance should have a different instance name. If not specified, this will be a generated random hostname. -
changeFeedProcessorOptions: Sets additional options for the change feed processor.
The consumer will set List<Map<String,>> in exchange message body which reflect the list of items in a single feed.
Example
For example, to listen to the events in myContainer container in myDb:
-
Java
-
XML
-
YAML
from("azure-cosmosdb://myDb/myContainer?leaseDatabaseName=myLeaseDb&createLeaseDatabaseIfNotExists=true&createLeaseContainerIfNotExists=true")
.to("mock:result"); <route>
<from uri="azure-cosmosdb://myDb/myContainer?leaseDatabaseName=myLeaseDb&createLeaseDatabaseIfNotExists=true&createLeaseContainerIfNotExists=true"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: azure-cosmosdb://myDb/myContainer
parameters:
leaseDatabaseName: myLeaseDb
createLeaseDatabaseIfNotExists: true
createLeaseContainerIfNotExists: true
steps:
- to:
uri: mock:result Important Development Notes
When developing on this component, in addition to the mocked unit tests, you will need to run the integration tests with every change you make or even client upgrade as the Azure client can break things even on minor versions upgrade. The integration tests run against a local Floci AZ container, which needs Docker. To run them, on this component directory, run the following maven command:
mvn verify Floci AZ does not emulate the change feed, the throughput of the databases, and the queries of the databases and containers, so six tests run against an Azure Cosmos DB account only: CosmosDbConsumerIT, CosmosDbContainerOperationsIT.testCaptureChangeFeed, CosmosDbProducerIT.testReplaceDatabaseThroughput, CosmosDbProducerIT.testQueryContainers, CosmosDbClientOperationsIT.testQueryAndReadAllDatabases and CosmosDbDatabaseOperationsIT.testQueryAndReadAllContainers. To run all the integration tests against an account in Azure, run the following maven command instead:
mvn verify -Dendpoint={{dbaddress}} -DaccessKey={{accessKey}} Whereby endpoint is your Azure CosmosDB endpoint name and accessKey is the access key being generated from Azure CosmosDB portal.