Couchbase
Since Camel 2.19
Both producer and consumer are supported
The couchbase: component allows you to treat Couchbase instances as a producer or consumer of messages.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-couchbase</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> 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 Couchbase component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
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 | |
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 | |
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 Couchbase endpoint is configured using URI syntax:
couchbase:protocol://hostname:port
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The scheme of the endpoint address, such as http, which is needed to parse the address. The connection to the cluster does not use it: the SDK connects to the hostname and the additionalHosts with its default ports, unless connectionString is set. | String | ||
Required The host name of a node of the Couchbase cluster, which the SDK bootstraps the connection from, together with the additionalHosts. Not used when connectionString is set. | String | ||
The port in the endpoint address. The connection to the cluster does not use it: the SDK connects to the hostname with its default ports (11210 for key-value operations). Set connectionString to connect to other ports. | 8091 | int |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The name of the bucket that holds the documents. | String | ||
The name of the collection, in the scope option, that holds the documents. When not set, the default collection of the bucket is used. | String | ||
The id of the document the producer puts, gets or deletes, when the message has no CamelCouchbaseId header. | String | ||
The name of the scope of the collection option. When not set, the default scope. The consumer also runs its SQL++ queries on this scope. Without the collection option the documents are read from and written to the default collection of the bucket, whatever the scope. | String | ||
What the consumer does with a document after its message is processed: delete removes it from the collection when the exchange completes (a failed exchange keeps it for the next poll); none and filter leave it in place, so the next poll reads it again. | none | String | |
The delay in milliseconds between two tries when the consumer reads a document (fullDocument=true) or removes one (consumerProcessedStrategy=delete) and the SDK retries the failure. The read is not tried again after queryTimeout, the remove after the timeout of producerRetryAttempts. | 5000 | int | |
If true, the built SQL query orders the documents by id in descending order (ORDER BY META().id DESC), and the view query returns its rows in descending key order. If false, the SQL query has no ORDER BY and the view query returns ascending order. Not used when statement is set. | false | boolean | |
Deprecated The name of the design document that holds the view, with useView=true. Deprecated: use SQL++ queries, such as with the statement option, instead. | beer | String | |
If true, the consumer reads each document the query finds by its id, and the message body is the GetResult of the SDK. If false, no document is read: the body is the row of the SQL++ query as JSON text, or the value the view emits. A row of a reduce view has no id, so its value is the body in both cases. | true | boolean | |
The most rows the built SQL++ query (LIMIT) or the view query returns in a poll; 0 or less means no limit. Not used when statement is set. | -1 | int | |
The highest document id the built SQL++ query returns (META().id ⇐ value). With useView=true the end key of the view query, which is used only together with rangeStartKey. Not used when statement is set. | String | ||
The lowest document id the built SQL++ query returns (META().id >= value). With useView=true the start key of the view query, which is used only together with rangeEndKey. Not used when statement is set. | String | ||
If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | false | boolean | |
How many rows the built SQL++ query (OFFSET) or the view query skips; 0 or less skips none. Not used when statement is set. | -1 | int | |
The SQL++ (N1QL) query the consumer polls with, instead of a view query or the query it builds from the options. Each row must hold the document id as id (SELECT META().id AS id, …): a row without it is skipped. The query runs on the scope (the default scope when the scope option is not set), with request_plus scan consistency, so a single name in FROM is a collection of that scope; use bucket.scope.collection for another one. Example: SELECT META().id AS __id, * FROM _default WHERE type = 'order' LIMIT 100. When not set and useView is false, the query is built from the collection, limit, skip, descending, rangeStartKey and rangeEndKey options. | String | ||
If true, the consumer polls with the view query of designDocumentName and viewName (MapReduce views are deprecated by Couchbase). If false, it polls with a SQL++ query. Not used when statement is set. | false | boolean | |
Deprecated The name of the view in the design document, with useView=true. Deprecated: use SQL++ queries, such as with the statement option, instead. | brewery_beers | 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 | ||
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 | ||
If true, the producer ignores the CamelCouchbaseId header and the key option, and uses a number as the document id, for every operation: startingIdForInsertsFrom for the first message, and one more for each next message. The counter is kept in memory, so it starts again from startingIdForInsertsFrom when the producer is created again. | false | boolean | |
The operation to do: CCB_PUT stores the message body as the document (upsert), CCB_GET reads the document and CCB_DEL removes it. Enum values:
| CCB_PUT | String | |
On how many nodes CCB_PUT waits for the document to be persisted to disk before it returns (the observe based durability of the SDK): 0 does not wait, 1 waits for the active node, and 2 to 4 for that many nodes, the active node and replicas. Other values fail when the producer is created, and the SDK fails the upsert when the bucket has fewer replicas configured. CCB_DEL does not use it. | 0 | int | |
Not a number of tries: producerRetryAttempts times producerRetryPause is the timeout of CCB_PUT and CCB_DEL (and of the remove of the consumer), or queryTimeout when that is longer. Within this timeout the SDK retries a failed operation that it considers retryable, with producerRetryPause between two tries. | 2 | int | |
The delay in milliseconds between two tries of a producer operation that failed with an error the SDK retries. The operation is not tried again after its timeout: queryTimeout for CCB_GET, and the one of producerRetryAttempts for CCB_PUT and CCB_DEL. | 5000 | int | |
To how many replicas CCB_PUT waits for the document to be replicated (in memory) before it returns (the observe based durability of the SDK): 0 does not wait, 1 to 3 waits for that many replicas. Other values fail when the producer is created, and the SDK fails the upsert when the bucket has fewer replicas configured. CCB_DEL does not use it. | 0 | int | |
The document id of the first message with autoStartIdForInserts=true: each next message gets this number plus one. Not used otherwise. | long | ||
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 | |
More host names of nodes of the cluster to bootstrap the connection from, separated by commas. Not used when connectionString is set. | String | ||
The connection string of the Couchbase SDK, such as couchbase://host1,host2 or couchbases://host for TLS, with a port when the key-value port is not 11210. When set, it is used instead of the hostname, port and additionalHosts options. | String | ||
The connect timeout of the SDK in milliseconds: how long it waits to connect to a node and to open the bucket. | 30000 | long | |
The timeout in milliseconds of CCB_GET and of the read of a document by the consumer. It is also the shortest timeout of CCB_PUT, CCB_DEL and the remove of the consumer (see producerRetryAttempts). A value other than 2500 also sets the SQL++ query timeout of the SDK; with 2500 the SDK default of 75 seconds applies. View queries always use the SDK default. | 2500 | long | |
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 | |
How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off. | 0 | long | |
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 | |
The password of the Couchbase user. The connection fails when it is not set. | String | ||
The name of the Couchbase user that the SDK authenticates as. The connection fails when it is not set. | String |
Message Headers
The Couchbase component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The key of the view row, as text: a key that is not a string, such as the compound key [2024, orders], as its JSON text. Only with useView=true. | String | |
| Constant: | The id of the document. The consumer sets it on each message, except for a row of a reduce view. The producer works on the document with this id, else on the one of the key option, and leaves the header on the message. | String | |
| Constant: | The expiry of the document that CCB_PUT stores, in seconds. 0, the default, means the document does not expire. | String | |
CamelCouchbaseDesignDocumentName (consumer) Constant: | The name of the design document of the view query. Only with useView=true. | String | |
CamelCouchbaseViewName (consumer) Constant: | The name of the view of the view query. Only with useView=true. | String | |
CamelCqlResumeQuery (consumer) Constant: | Not a message header: the name of the ResumeAction bean that the consumer looks up in the registry when it starts with a resume strategy. | String |
Message Body
The message body at each side of the Couchbase 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 |
| One message per document the query finds, read by its id (the CamelCouchbaseId header) as the GetResult of the Couchbase SDK: contentAsObject() gives the JSON document. With fullDocument=false the row of the SQL++ query as JSON text, or with useView=true the value the view emits. A row of a reduce view has no id: its value is the body, also with fullDocument=true.
|
Producer input |
| The document that CCB_PUT, the default, stores: text or bytes that hold a JSON object or array as that JSON document, other text as a JSON string, other bytes as a binary document, and a stream is read as bytes. A Map, a List or a POJO becomes JSON. No body fails. CCB_GET and CCB_DEL do not use the body: the id is the CamelCouchbaseId header, else the key option. Not known when |
Producer output |
| true for CCB_PUT, the default; the GetResult of the Couchbase SDK for CCB_GET, and the MutationResult as text for CCB_DEL. The CamelCouchbaseId header stays on the message.
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.
Consuming documents
The consumer supports two query modes for polling documents from Couchbase:
SQL++ queries (recommended, default)
Since Couchbase Server 7.0, the recommended way to query documents is using SQL++ (formerly N1QL). MapReduce Views are deprecated since Couchbase 7.0 and do not work with the Magma storage backend (default since Couchbase 8.0).
By default, the consumer uses SQL++ queries. You can either provide an explicit statement or let the consumer auto-generate one from the endpoint options.
Auto-generated queries
The simplest way to consume documents is to just use the existing endpoint options. The consumer auto-generates a SQL++ query from bucket, collection, limit, skip, descending, rangeStartKey, and rangeEndKey:
-
Java
-
XML
-
YAML
from("couchbase:http://localhost?bucket=myBucket&username=user&password=pass&limit=10&descending=true")
.to("direct:result"); <route>
<from uri="couchbase:http://localhost?bucket=myBucket&username=user&password=pass&limit=10&descending=true"/>
<to uri="direct:result"/>
</route> - route:
from:
uri: couchbase:http://localhost
parameters:
bucket: myBucket
username: user
password: pass
limit: 10
descending: true
steps:
- to:
uri: direct:result This generates: SELECT META().id AS \__id, * FROM \`myBucket\.`_default\`.`_default\` AS `myBucket\` ORDER BY META().id DESC LIMIT 10`
The query runs on the scope of the endpoint (the default scope when scope is not set). With the collection option, the query reads that collection of the scope (FROM \`myCollection\`). Without it, the query reads the default collection of the bucket, which is the collection the consumer fetches the documents from.
Explicit SQL++ statements
For complex queries (filters, joins, aggregations), set the statement option directly:
from("couchbase:http://localhost?bucket=myBucket&username=user&password=pass"
+ "&statement=SELECT META().id AS __id, * FROM `_default` WHERE type = 'order' LIMIT 100")
.to("direct:result"); The query must include META().id AS \__id in the SELECT clause so the consumer can identify each document.
The statement runs on the scope of the endpoint (the default scope when scope is not set), so a single name in FROM is a collection of that scope: in the default scope, FROM \`_default` is the default collection of the bucket, and the bucket name alone fails with "Keyspace not found". Use the full path \`bucket\.`scope\`.`collection\`` for a collection of another scope.
When fullDocument is true (the default), the consumer fetches the document from the KV store by its id, and the message body is the GetResult of the Couchbase SDK, with the id in the CamelCouchbaseId header: contentAsObject() gives the JSON document. When false, the message body is the query result row as JSON text, or with views the value the view emits.
SQL++ queries require a primary index or appropriate secondary index on the bucket/collection. Create one with: CREATE PRIMARY INDEX ON \`myBucket\` or via the Couchbase SDK. |
MapReduce Views (deprecated)
The consumer can also poll documents using MapReduce Views by setting useView=true with the designDocumentName and viewName endpoint options. This mode is deprecated and will be removed in a future release.
from("couchbase:http://localhost?bucket=myBucket&username=user&password=pass"
+ "&useView=true&designDocumentName=myDoc&viewName=myView&limit=10")
.to("direct:result"); Reduce views and compound keys work in view mode too. A row of a reduce view has no document ID: its value is the message body, with or without fullDocument, and the CamelCouchbaseId header is not set. A key that is not a string, such as the compound key [2024, "orders"], is set in the CamelCouchbaseKey header as its JSON text.
Migrating from Views to SQL++
To migrate from MapReduce Views to SQL, simply remove `designDocumentName` and `viewName` from your endpoint URI. The `limit`, `skip`, `descending`, `rangeStartKey`, and `rangeEndKey` options are automatically translated to SQL clauses:
| View option | SQL++ equivalent |
|---|---|
| Removed (or replaced by |
|
|
|
|
|
|
|
|
| Works the same way in both modes |
For example, a view-based consumer:
from("couchbase:http://localhost?bucket=myBucket&username=user&password=pass"
+ "&useView=true&designDocumentName=myDoc&viewName=myView&limit=10&descending=true") Can be migrated by simply removing the view-specific options:
from("couchbase:http://localhost?bucket=myBucket&username=user&password=pass"
+ "&limit=10&descending=true") Or with an explicit SQL++ statement for more control:
from("couchbase:http://localhost?bucket=myBucket&username=user&password=pass"
+ "&statement=SELECT META().id AS __id, * FROM `_default` ORDER BY META().id DESC LIMIT 10") Producing documents
The producer works on one document per message. The document id is the CamelCouchbaseId header, or the key option when the message has no such header. The call fails when neither gives an id, unless autoStartIdForInserts is enabled, which gives every document the next number as id. The producer leaves the CamelCouchbaseId header on the message, so a CCB_GET after a CCB_PUT in the same route reads the document the CCB_PUT stored.
The operation option is one of the following; any other value fails when the producer starts:
| Operation | What it does | Message body afterwards |
|---|---|---|
| Stores the message body as the document (an upsert), with the expiry of the |
|
| Reads the document | The |
| Removes the document | The text of the |
CCB_PUT stores the message body as follows:
| Message body | Stored as |
|---|---|
Text ( | That JSON document, as it is ( |
Other text | A JSON string |
| That JSON document, as it is ( |
Other | A binary document ( |
A stream ( | Read as bytes, and then stored as a |
A | A JSON document, serialized by the SDK |
Couchbase SDK compatibility
Using collections and scopes is supported only for Couchbase Server 7.0 and later.
This component is currently using Java SDK 3.x, so it might be not compatible with older Couchbase servers anymore. Check the compatibility page for details.
-
The value formerly interpreted as a bucket-name is now interpreted as a username. The username must correspond to a user defined on the cluster that is being accessed.
-
The value formerly interpreted as a bucket-password is now interpreted as the password of the defined user.