Camel Components

ClickHouse

Since Camel 4.22

Only producer is supported

This component allows you to interact with ClickHouse, the high-performance columnar OLAP database, using the official ClickHouse Java client (client-v2).

While ClickHouse can be reached through the generic JDBC and SQL components, this dedicated component exposes ClickHouse’s native capabilities as first-class endpoint options: native format streaming inserts (RowBinary, JSONEachRow, CSV, TSV, Parquet), server-side asynchronous inserts, OLAP queries and health checks.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-clickhouse</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

clickhouse://database[.table]?[options]

The producer can either use a shared com.clickhouse.client.api.Client bean (autowired from the registry) or build its own client from the serverUrl, username, password and ssl options. Connection settings can also be configured once on the component (for example camel.component.clickhouse.serverUrl) and inherited by every endpoint, so they do not need to be repeated in each URI.

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, *.yaml files, 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 ClickHouse component supports the following options which are listed below.

Name Description Default Type

client (producer)

Autowired The shared ClickHouse client (com.clickhouse.client.api.Client) that all the endpoints of this component use, for settings this component has no option for (such as a trust store or timeouts). An insert of a List body needs it, as the class of the objects must be registered on it with Client.register(Class, TableSchema). When set, the endpoints do not create their own client, and the serverUrl, username, password, ssl and compression options are not used.

Client

compression (producer)

Whether the client compresses the body of each request it sends (the data of an insert, the SQL of a query) in the ClickHouse compressed block format, with ZSTD, the default compression method of the client. Not used when a shared client is set.

false

boolean

lazyStartProducer (producer)

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

serverUrl (producer)

The URL of the ClickHouse HTTP interface, with scheme and port, such as http://localhost:8123 (the port is required). Used by every endpoint that does not set its own serverUrl. Not used when a shared client is set.

String

autowiredEnabled (advanced)

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

password (security)

The password of the ClickHouse user. Empty when not set. Not used when a shared client is set.

String

ssl (security)

Whether to connect over HTTPS: the http:// scheme of serverUrl (or a URL without scheme) is changed to https://, but the port is not, so serverUrl must give the HTTPS port of the server (such as 8443). A serverUrl that starts with https:// uses HTTPS also when this option is false. The client checks the server certificate and host name against the default trust store of the JVM. Not used when a shared client is set.

false

boolean

username (security)

The name of the ClickHouse user. The client sends it with the password in HTTP basic authentication on each request. Not used when a shared client is set.

default

String

Endpoint Options

The ClickHouse endpoint is configured using URI syntax:

clickhouse:database

With the following path and query parameters:

Path Parameters

Name Description Default Type

database (producer)

Required The ClickHouse database that inserts and queries run in. A table may also be given in the path, as database.table.

String

Query Parameters

Name Description Default Type

asyncInsert (producer)

Whether an insert uses the asynchronous inserts of ClickHouse (the async_insert setting): the server buffers the data and writes it to the table later, together with the data of other inserts.

false

boolean

batchSize (producer)

The client-side batch size for insert operations when the message body is a List. When greater than 0, the list is split into batches of this size and each batch is sent as a separate insert. A value of 0 (default) inserts the whole list in a single call.

0

int

compression (producer)

Whether the client compresses the body of each request it sends (the data of an insert, the SQL of a query) in the ClickHouse compressed block format, with ZSTD, the default compression method of the client. Not used when a shared client is set on the component.

false

boolean

format (producer)

The ClickHouse data format of the data that an insert sends and of the result of a query, such as JSONEachRow, CSV, TSV, RowBinary or Parquet. The value is the name of a constant of the ClickHouseFormat enum of the client, and is case-sensitive. Not used when the body of an insert is a List, as the client then sends the objects as RowBinary.

JSONEachRow

String

operation (producer)

The operation to perform: insert writes the message body to the table, query runs the SQL statement of the message body and returns its result, and ping checks that the server answers.

Enum values:

  • INSERT

  • QUERY

  • PING

INSERT

ClickHouseOperation

serverUrl (producer)

The URL of the ClickHouse HTTP interface, with scheme and port, such as http://localhost:8123 (the port is required). Required unless a shared client is set on the component (or autowired from the registry), which is then used instead.

String

table (producer)

The table that an insert writes to. Can also be given in the path as database.table, or per message with the CamelClickHouseTable header when allowDatabaseAndTableFromHeaders is enabled. Not used by query and ping.

String

waitForAsyncInsert (producer)

When asyncInsert is enabled, whether the server answers the insert only after the buffered data is written to the table (the wait_for_async_insert setting). When false, the server answers as soon as the data is buffered, and does not report an error that happens when the data is written later.

true

boolean

lazyStartProducer (producer (advanced))

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

allowDatabaseAndTableFromHeaders (security)

Whether to allow overriding the database and the table of the endpoint with the CamelClickHouseDatabase and CamelClickHouseTable headers. Disabled by default; enable it only when the header source is trusted, since it lets a message choose the database that an insert or a query runs in and the table that an insert writes to.

false

boolean

password (security)

The password of the ClickHouse user. Empty when not set. Not used when a shared client is set on the component.

String

ssl (security)

Whether to connect over HTTPS: the http:// scheme of serverUrl (or a URL without scheme) is changed to https://, but the port is not, so serverUrl must give the HTTPS port of the server (such as 8443). A serverUrl that starts with https:// uses HTTPS also when this option is false. The client checks the server certificate and host name against the default trust store of the JVM. Not used when a shared client is set on the component.

false

boolean

username (security)

The name of the ClickHouse user. The client sends it with the password in HTTP basic authentication on each request. Not used when a shared client is set on the component.

default

String

Message Headers

The ClickHouse component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelClickHouseOperation (producer)

Constant: OPERATION

Overrides the operation configured on the endpoint: insert, query or ping (in any case).

String

CamelClickHouseDatabase (producer)

Constant: DATABASE

Overrides the target database configured on the endpoint. This header is ignored unless the endpoint enables allowDatabaseAndTableFromHeaders=true (disabled by default).

String

CamelClickHouseTable (producer)

Constant: TABLE

Overrides the target table configured on the endpoint. This header is ignored unless the endpoint enables allowDatabaseAndTableFromHeaders=true (disabled by default).

String

CamelClickHouseFormat (producer)

Constant: FORMAT

Overrides the data format configured on the endpoint. The value is the name of a constant of the ClickHouseFormat enum of the client, such as JSONEachRow, and is case-sensitive.

String

CamelClickHouseWrittenRows (producer)

Constant: WRITTEN_ROWS

The number of rows that an insert wrote, as reported by the server. When batchSize splits a List body, the sum of all the batches.

long

CamelClickHouseReadRows (producer)

Constant: READ_ROWS

The number of rows the server read (scanned) to run a query operation. This is not the number of rows in the result: with a WHERE or a LIMIT it is usually more.

long

CamelClickHousePingOk (producer)

Constant: PING_OK

The result of a ping, also set as the message body: true when the server answered a SELECT 1 query, false when the query failed for any reason (the ping does not throw an exception).

boolean

Message Body

The message body at each side of the ClickHouse 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

Producer input

text, bytes, stream, file or list

The rows to insert, in the format option (JSONEachRow: one JSON object per line), as text, bytes, a stream or a file; or a List of objects whose class is registered on the Client. A Map or a List of Maps fails: marshal it first. Query takes the SQL statement.

  • With operation=QUERY: text, bytes, stream or file

  • With operation=PING: any

Producer output

unchanged

Insert leaves the body unchanged, with the count in the CamelClickHouseWrittenRows header. Query gives the result in the format option: a String for text formats (JSONEachRow: one JSON object per line), a byte[] for binary formats such as RowBinary, Native or Parquet. Ping gives a Boolean. The CamelClickHouseOperation header overrides the operation.

  • With operation=QUERY: text or bytes

  • With operation=PING: value (java.lang.Boolean)

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.

Operations

The component is producer-only and supports the following operations, selected with the operation option or the CamelClickHouseOperation header:

Operation Description

insert (default)

Streams the message body into the target table using the configured format. Accepted body types are InputStream, byte[], String, java.io.File (matched to the format), or a List of objects whose class has been registered on the shared Client with Client.register(Class, TableSchema). A List of Map is not supported: marshal the rows to the format (such as JSONEachRow) first. When the body is a List and batchSize is greater than 0, the list is split into batches of that size, each sent as a separate insert. An empty List is a 0-row insert: nothing is sent to ClickHouse. The number of written rows is set on the CamelClickHouseWrittenRows header.

query

Runs the SQL statement contained in the message body and returns the result set in the configured format: a String body for text formats (such as JSONEachRow, CSV or TSV), and a byte[] body for binary formats (such as RowBinary, Native, Parquet, Arrow or Avro). The CamelClickHouseReadRows header is set to the number of rows the server read to run the query, which is not the number of rows in the result.

ping

Pings the ClickHouse server and sets the boolean result on both the message body and the CamelClickHousePingOk header.

Headers that override the endpoint

The CamelClickHouseOperation and CamelClickHouseFormat headers take the place of the operation and format options for one message. As query runs the message body as SQL, a message that sets CamelClickHouseOperation to query on an insert endpoint chooses the SQL that runs.

The CamelClickHouseDatabase and CamelClickHouseTable headers are ignored unless the endpoint sets allowDatabaseAndTableFromHeaders=true. With that option, they take the place of the database and the table of the endpoint for one message, so the message chooses the database that an insert or a query runs in and the table that an insert writes to.

When the messages come from an untrusted producer through a consumer that does not filter out Camel* headers, remove these headers with removeHeaders("CamelClickHouse*") before the clickhouse endpoint.

Examples

High-throughput event ingestion

Batch-insert aggregated events into ClickHouse using the native RowBinary format:

  • Java

  • YAML

from("kafka:events?groupId=analytics")
    .aggregate(constant(true), new GroupedBodyAggregationStrategy())
        .completionSize(5000).completionTimeout(2000)
    .to("clickhouse://analytics.events?operation=insert&format=RowBinary")
    .log("Inserted ${header.CamelClickHouseWrittenRows} rows");
- route:
    from:
      uri: kafka:events
      parameters:
        groupId: analytics
      steps:
        - aggregate:
            correlationExpression:
              constant:
                expression: "true"
            aggregationStrategy: "#class:org.apache.camel.processor.aggregate.GroupedBodyAggregationStrategy"
            completionSize: 5000
            completionTimeout: "2000"
            steps:
              - to:
                  uri: clickhouse://analytics.events
                  parameters:
                    operation: insert
                    format: RowBinary
              - log:
                  message: "Inserted ${header.CamelClickHouseWrittenRows} rows"

Server-side asynchronous inserts

Let ClickHouse buffer and flush inserts server-side, ideal for many concurrent producers sending small payloads:

  • Java

  • YAML

from("platform-http:/ingest")
    .to("clickhouse://metrics.samples?operation=insert&asyncInsert=true&waitForAsyncInsert=false");
- route:
    from:
      uri: platform-http:/ingest
      steps:
        - to:
            uri: clickhouse://metrics.samples
            parameters:
              operation: insert
              asyncInsert: true
              waitForAsyncInsert: false

Scheduled OLAP query

Run an aggregation query on a timer and route the result set downstream:

  • Java

  • YAML

from("timer:rollup?period=60000")
    .setBody(constant("SELECT count() FROM analytics.events"))
    .to("clickhouse://analytics?operation=query&format=JSONEachRow")
    .to("kafka:rollup-metrics");
- route:
    from:
      uri: timer:rollup
      parameters:
        period: 60000
      steps:
        - setBody:
            expression:
              constant:
                expression: "SELECT count() FROM analytics.events"
        - to:
            uri: clickhouse://analytics
            parameters:
              operation: query
              format: JSONEachRow
        - to:
            uri: kafka:rollup-metrics

Health check

Verify connectivity to the ClickHouse server:

  • Java

  • YAML

from("timer:health?period=30000")
    .to("clickhouse://default?operation=ping")
    .choice()
        .when(header("CamelClickHousePingOk").isEqualTo(true))
            .to("direct:markHealthy")
        .otherwise()
            .to("direct:alertOps")
    .end();
- route:
    from:
      uri: timer:health
      parameters:
        period: 30000
      steps:
        - to:
            uri: clickhouse://default
            parameters:
              operation: ping
        - choice:
            when:
              - expression:
                  simple:
                    expression: "${header.CamelClickHousePingOk} == true"
                steps:
                  - to:
                      uri: direct:markHealthy
            otherwise:
              steps:
                - to:
                    uri: direct:alertOps