Elasticsearch
Since Camel 3.19
Only producer is supported
The Elasticsearch component allows you to interface with an Elasticsearch 8.x API using the Java API Client library.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-elasticsearch</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 Elasticsearch component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
The connect timeout in milliseconds: the longest time that the client waits to establish the connection to a node. Not used when the client option is set. | 30000 | int | |
Whether the body of Update is only the partial document to merge into the document. If false, the body is the request body of the Update API, such as \{doc: \{…}} or a script. Only JSON text, bytes, a stream, a file or a Map is read this way. The CamelElasticsearchEnableDocumentOnlyMode header replaces this option. | false | boolean | |
The comma-separated list of the nodes to connect to, each as host:port, for example es1:9200,es2:9200. The port is 9200 if not set, and the scheme is https when enableSSL is set. Required unless the client option is set. | 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 | |
Deprecated Deprecated: this option has no effect. It was used by the old low-level REST client and is ignored by the current client. | 30000 | int | |
The socket timeout in milliseconds: the longest time that the client waits for data from a node before the request fails. Not used when the client option is set. | 30000 | int | |
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 | |
Autowired To use an existing org.elasticsearch.client.RestClient, shared by all the endpoints of the component, instead of a client that each producer creates. The hostAddresses, timeout, authentication, SSL, sniffer and disconnect options are then not used, and the producers do not close the client. | RestClient | ||
Whether to start the Sniffer of the Elasticsearch REST client, which reads the nodes of the cluster from its Nodes Info API at an interval and updates the nodes that the client uses. Not used when the client option is set or autowired, as Spring Boot does. | false | boolean | |
The delay in milliseconds of the read of the nodes that the Sniffer schedules after a failed request, when enableSniffer is set. | 60000 | int | |
The interval in milliseconds between two reads of the nodes of the cluster, when enableSniffer is set. | 300000 | int | |
API key to authenticate with, sent in the Authorization header instead of a user and password. Either the encoded key as Elasticsearch shows it when the key is created, or the id and the key separated by a colon (id:key). The key is only sent to the configured hosts and the nodes found by the sniffer. | String | ||
The CA certificate, in X.509 format, that the client trusts for HTTPS instead of the default trust store of the JVM. It is loaded from the classpath by default, or with the prefix classpath:, file: or http:. It needs enableSSL, and sslContextParameters takes precedence. | String | ||
Whether to connect to the nodes of hostAddresses with HTTPS instead of HTTP. The default SSLContext of the JVM is used unless sslContextParameters or certificatePath is set. | false | boolean | |
The password for HTTP basic authentication to the nodes, used only together with user. Not used when the client option is set. | String | ||
To configure security using SSLContextParameters, which sets the protocols, cipher suites, named groups and signature schemes of the HTTPS connection. It takes precedence over certificatePath, and it needs enableSSL. | SSLContextParameters | ||
Whether to use the global SSLContextParameters of the CamelContext for an endpoint that has no sslContextParameters. | false | boolean | |
The user name for HTTP basic authentication to the nodes, used only together with password. It cannot be combined with apiKey. Not used when the client option is set. | String |
Endpoint Options
The Elasticsearch endpoint is configured using URI syntax:
elasticsearch:clusterName
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The connect timeout in milliseconds: the longest time that the client waits to establish the connection to a node. Not used when the client option of the component is set. | 30000 | int | |
Whether the producer creates the client for each exchange and closes it when the exchange is done, or with useScroll when the scroll iterator is closed, instead of keeping one client from its start to its stop. Not used when the client option of the component is set. | false | boolean | |
Whether the body of Update is only the partial document to merge into the document. If false, the body is the request body of the Update API, such as \{doc: \{…}} or a script. Only JSON text, bytes, a stream, a file or a Map is read this way. The CamelElasticsearchEnableDocumentOnlyMode header replaces this option. | false | boolean | |
The offset of the first hit that Search returns when the body is JSON text or a Map. It replaces the from of the body, and the CamelElasticsearchFrom header replaces this option. | Integer | ||
The comma-separated list of the nodes to connect to, each as host:port, for example es1:9200,es2:9200. The port is 9200 if not set, and the scheme is https when enableSSL is set. Required unless the client option of the component is set. | String | ||
The name of the index that the operation acts on. Bulk uses it as the default index of its operations, and DeleteIndex deletes this index instead of the one named by the body. The CamelElasticsearchIndexName header replaces this option, and a request of the Elasticsearch Java API Client in the body keeps its own index. | String | ||
Deprecated Deprecated: this option has no effect. It was used by the old low-level REST client and is ignored by the current client. | 30000 | int | |
The operation that the producer performs. The CamelElasticsearchOperation header replaces this option. A request of the Elasticsearch Java API Client in the body, such as an IndexRequest or a SearchRequest, sets the operation by its type and replaces both. Enum values:
| ElasticsearchOperation | ||
The time in milliseconds that Elasticsearch keeps the search context of a scroll alive between two scroll requests, when useScroll is set. The CamelElasticsearchScrollKeepAliveMs header replaces this option. | 60000 | int | |
The maximum number of hits that Search returns when the body is JSON text or a Map. It replaces the size of the body, and the CamelElasticsearchSize header replaces this option. | Integer | ||
The socket timeout in milliseconds: the longest time that the client waits for data from a node before the request fails. Not used when the client option of the component is set. | 30000 | int | |
Whether Search reads all the hits with the scroll API. The body is then an ElasticsearchScrollRequestIterator of the hits, which sends the scroll requests while it is read and is to be closed after use. The CamelElasticsearchUseScroll header replaces this option. | false | boolean | |
The number of active shard copies that Index and Update wait for before they write. The default of 1 waits only for the primary shard. The CamelElasticsearchWaitForActiveShards header replaces this option. | 1 | int | |
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 class to which the documents in the responses of GetById, MultiGet, Search and MultiSearch are deserialized. The default is the Jackson ObjectNode. The CamelElasticsearchDocumentClass header replaces this option. | ObjectNode | Class | |
Whether to start the Sniffer of the Elasticsearch REST client, which reads the nodes of the cluster from its Nodes Info API at an interval and updates the nodes that the client uses. Not used when the client option of the component is set or autowired, as Spring Boot does. | false | boolean | |
The delay in milliseconds of the read of the nodes that the Sniffer schedules after a failed request, when enableSniffer is set. | 60000 | int | |
The interval in milliseconds between two reads of the nodes of the cluster, when enableSniffer is set. | 300000 | int | |
The CA certificate, in X.509 format, that the client trusts for HTTPS instead of the default trust store of the JVM. It is loaded from the classpath by default, or with the prefix classpath:, file: or http:. It needs enableSSL, and sslContextParameters takes precedence. | String | ||
Whether to connect to the nodes of hostAddresses with HTTPS instead of HTTP. The default SSLContext of the JVM is used unless sslContextParameters or certificatePath is set. | false | boolean | |
To configure security using SSLContextParameters, which sets the protocols, cipher suites, named groups and signature schemes of the HTTPS connection. It takes precedence over certificatePath, and it needs enableSSL. | SSLContextParameters |
Message Headers
The Elasticsearch component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelElasticsearchOperation (producer) Constant: | The operation that the producer performs. It replaces the operation option. A request of the Elasticsearch Java API Client in the body sets the operation by its type and replaces both. Enum values:
| ElasticsearchOperation | |
CamelElasticsearchIndexId (producer) Constant: | The id of the document for Index and Update. If it is not set for Index, Elasticsearch generates the id. | String | |
CamelElasticsearchIndexName (producer) Constant: | The name of the index that the operation acts on. It replaces the indexName option. | String | |
CamelElasticsearchDocumentClass (producer) Constant: | The class to which the documents in the responses of GetById, MultiGet, Search and MultiSearch are deserialized. It replaces the documentClass option. | ObjectNode | Class |
CamelElasticsearchWaitForActiveShards (producer) Constant: | The number of active shard copies that Index and Update wait for before they write. It replaces the waitForActiveShards option. | Integer | |
CamelElasticsearchScrollKeepAliveMs (producer) Constant: | The time in milliseconds that Elasticsearch keeps the search context of a scroll alive between two scroll requests. It replaces the scrollKeepAliveMs option. | Integer | |
CamelElasticsearchUseScroll (producer) Constant: | Whether Search reads all the hits with the scroll API. It replaces the useScroll option. | Boolean | |
CamelElasticsearchSize (producer) Constant: | The maximum number of hits that Search returns when the body is JSON text or a Map. It replaces the size option. | Integer | |
CamelElasticsearchFrom (producer) Constant: | The offset of the first hit that Search returns when the body is JSON text or a Map. It replaces the from option. | Integer | |
CamelElasticsearchEnableDocumentOnlyMode (producer) Constant: | Whether the body of Update is only the partial document to merge into the document. It replaces the enableDocumentOnlyMode option. | false | Boolean |
Message Body
The message body at each side of the Elasticsearch 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 |
| By the operation, set by the operation option or the CamelElasticsearchOperation header, or by the request of the Elasticsearch client in the body. Index and Update take the document as JSON text, bytes, a stream or a file of it, or a Map or a POJO (written as JSON); text that is not JSON, a List or no body fail. Update expects the Update API form, {"doc": {…}}, unless enableDocumentOnlyMode is set. GetById and Delete take the id as text, Bulk and MultiGet a List of documents or ids, Search the search request as JSON text or a Map, with its query, size, sort, aggregations and the rest (an object with a single member other than query is the query alone), and DeleteIndex the name of the index as text, used when neither the CamelElasticsearchIndexName header nor indexName is set. Each also takes its request of the Elasticsearch client, or the builder of it, which is sent as it is; MultiSearch takes only those. Exists and Ping do not use the body.
|
Producer output |
| The id of the document as text for Index and Update. GetById gives the GetResponse of the Elasticsearch client (found() is false for no document), Search the HitsMetadata of the hits, or with useScroll an ElasticsearchScrollRequestIterator of the hits to close after use; the source of a hit is a Jackson ObjectNode unless documentClass is set. MultiGet, MultiSearch and Bulk give a List of the response item of each document or search, Delete the Result enum (Deleted or NotFound), and DeleteIndex, Exists and Ping a 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.
Message Operations
The following Elasticsearch operations are currently supported. Set an endpoint URI option or exchange header with a key of "operation" and a value set to one of the following. Some operations also require other parameters or the message body to be set.
A request of the Elasticsearch client in the message body, such as an IndexRequest, a GetRequest or a SearchRequest, sets the operation by its type, whatever the option or header say, and is sent as it is: its index, id and the rest are not changed by the headers or options.
| operation | message body | description |
|---|---|---|
Index | Map, String, byte[], Reader, InputStream, a file ( | Adds content to an index and returns the content’s indexId in the body. A file is read as the JSON of the document, and a null body fails. You can set the name of the target index by setting the message header with the key "indexName". You can set the indexId by setting the message header with the key "indexId". |
GetById | String, GetRequest or GetRequest.Builder index id of content to retrieve | Retrieves the document corresponding to the given index id and returns a |
Delete | String, DeleteRequest or DeleteRequest.Builder index id of content to delete | Deletes the specified indexName and returns a Result object in the body. You can set the name of the target index by setting the message header with the key "indexName". |
DeleteIndex | String name of the index, DeleteIndexRequest or DeleteIndexRequest.Builder | Deletes the index named by the indexName header or option, or else the one named by a |
Bulk | Iterable, BulkRequest or BulkRequest.Builder of any type that is already accepted (DeleteOperation.Builder for delete operation, UpdateOperation.Builder for update operation, CreateOperation.Builder for create operation, byte[], InputStream, String, Reader, Map or any document type for index operation) | Adds/Updates/Deletes content from/to an index and returns a List<BulkResponseItem> object in the body You can set the name of the target index by setting the message header with the key "indexName". |
Search | Map, String, SearchRequest or SearchRequest.Builder | Search the content with the search request as a JSON |
MultiSearch | MsearchRequest or MsearchRequest.Builder | Multiple search in one |
MultiGet | Iterable<String>, MgetRequest or MgetRequest.Builder the id of the document to retrieve | Multiple get in one You can set the name of the target index by setting the message header with the key "indexName". |
Exists | None | Check whether the index exists or not and returns a Boolean flag in the body. You must set the name of the target index by setting the message header with the key "indexName". |
Update | byte[], InputStream, String, Reader, Map, a file, UpdateRequest, UpdateRequest.Builder or any document type content to update | Updates content to an index and returns the content’s indexId in the body. A file is read as JSON, and a null body fails. You can set the name of the target index by setting the message header with the key "indexName". You can set the indexId by setting the message header with the key "indexId". Be aware of the fact that unlike the component camel-elasticsearch-rest, by default, the expected content of an update request must be the same as what the Update API expects, consequently if you want to update one part of an existing document, you need to embed the content to update into a "doc" object. To change the default behavior, it is possible to configure it globally at the component level thanks to the option enableDocumentOnlyMode or by request by setting the header |
Ping | None | Pings the Elasticsearch cluster and returns true if the ping succeeded, false otherwise |
Usage
Configure the component and enable basic authentication
To use the Elasticsearch component, it has to be configured with a minimum configuration.
ElasticsearchComponent elasticsearchComponent = new ElasticsearchComponent();
elasticsearchComponent.setHostAddresses("myelkhost:9200");
camelContext.addComponent("elasticsearch", elasticsearchComponent); For basic authentication with elasticsearch or using reverse http proxy in front of the elasticsearch cluster, simply setup basic authentication and SSL on the component like the example below
ElasticsearchComponent elasticsearchComponent = new ElasticsearchComponent();
elasticsearchComponent.setHostAddresses("myelkhost:9200");
elasticsearchComponent.setUser("elkuser");
elasticsearchComponent.setPassword("secure!!");
elasticsearchComponent.setEnableSSL(true);
elasticsearchComponent.setCertificatePath(certPath);
camelContext.addComponent("elasticsearch", elasticsearchComponent); Authenticate with an API key
Instead of a user and password, the component can log in with an Elasticsearch API key, which is what Elastic recommends, also on Elastic Cloud. Set the apiKey option to the encoded key as Elasticsearch shows it when the key is created (the encoded field of the response), or to the id and the key separated by a colon (id:key). Camel sends it as the Authorization: ApiKey … header.
camel.component.elasticsearch.host-addresses=myelkhost:9200
camel.component.elasticsearch.enable-ssl=true
camel.component.elasticsearch.api-key={{elasticsearch.api-key}} The key is only sent to the hosts of hostAddresses and to the nodes the sniffer finds, never to another host, such as the target of a redirect. Setting apiKey together with user and password fails when the endpoint is created; a user without a password is not used, and the apiKey is sent. When the component uses a client set with the client option, the apiKey option is not used, as for user and password.
Document type
For all the search operations, it is possible to indicate the type of document to retrieve to get the result already unmarshalled with the expected type.
The document type can be set using the header "documentClass" or via the uri parameter of the same name.
Using Camel Elasticsearch with Spring Boot
When you use camel-elasticsearch-starter with Spring Boot v2, then you must declare the following dependency in your own pom.xml.
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
<version>2.0.2</version>
</dependency> This is needed because Spring Boot v2 provides jakarta.json-api:1.1.6, and Elasticsearch requires to use json-api v2.
Use RestClient provided by Spring Boot
By default, Spring Boot will auto configure an Elasticsearch RestClient that will be used by camel, it is possible to customize the client with the following basic properties:
spring.elasticsearch.uris=myelkhost:9200
spring.elasticsearch.username=elkuser
spring.elasticsearch.password=secure!! Disable Sniffer when using Spring Boot
When Spring Boot is on the classpath, the Sniffer client for Elasticsearch is enabled by default. This option can be disabled in the Spring Boot Configuration:
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration Examples
Index Example
Below is a simple INDEX example
-
Java
-
XML
-
YAML
from("direct:index")
.to("elasticsearch://elasticsearch?operation=Index&indexName=twitter"); <route>
<from uri="direct:index"/>
<to uri="elasticsearch://elasticsearch?operation=Index&indexName=twitter"/>
</route> - route:
from:
uri: direct:index
steps:
- to:
uri: elasticsearch://elasticsearch
parameters:
operation: Index
indexName: twitter The indexId header (CamelElasticsearchIndexId) is optional: without it, the server generates the id of the document.
A client would simply need to pass a body message containing a Map to the route. The result body contains the indexId created.
Map<String, String> map = new HashMap<String, String>();
map.put("content", "test");
String indexId = template.requestBody("direct:index", map, String.class); Search Example
Searching on specific field(s) and value use the Operation ´Search´. Pass in the search request as a JSON String or a Map: its size, sort, aggregations and the other members are used with its query.
-
Java
-
XML
-
YAML
from("direct:search")
.to("elasticsearch://elasticsearch?operation=Search&indexName=twitter"); <route>
<from uri="direct:search"/>
<to uri="elasticsearch://elasticsearch?operation=Search&indexName=twitter"/>
</route> - route:
from:
uri: direct:search
steps:
- to:
uri: elasticsearch://elasticsearch
parameters:
operation: Search
indexName: twitter String query = "{\"query\":{\"match\":{\"content\":\"new release of ApacheCamel\"}},\"size\":5}";
HitsMetadata<?> response = template.requestBody("direct:search", query, HitsMetadata.class); Search on specific field(s) using Map.
Map queryMap<String, Object> actualQuery = new HashMap<>();
actualQuery.put("content", "new release of ApacheCamel");
Map<String, Object> match = new HashMap<>();
match.put("match", actualQuery);
Map<String, Object> query = new HashMap<>();
query.put("query", match);
HitsMetadata<?> response = template.requestBody("direct:search", query, HitsMetadata.class); Search using Elasticsearch scroll api to fetch all results.
-
Java
-
XML
-
YAML
from("direct:search")
.to("elasticsearch://elasticsearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000"); <route>
<from uri="direct:search"/>
<to uri="elasticsearch://elasticsearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000"/>
</route> - route:
from:
uri: direct:search
steps:
- to:
uri: elasticsearch://elasticsearch
parameters:
operation: Search
indexName: twitter
useScroll: true
scrollKeepAliveMs: 30000 String query = "{\"query\":{\"match\":{\"content\":\"new release of ApacheCamel\"}}}";
try (ElasticsearchScrollRequestIterator response = template.requestBody("direct:search", query, ElasticsearchScrollRequestIterator.class)) {
// do something smart with results
} The iterator sends a scroll request for each page while it is read, and clears the scroll when it is closed. It closes itself once hasNext() returns false at the end of the scroll. When you stop reading before the end, close the iterator, as above: with disconnect=true it holds the client of the exchange until it is closed.
Split EIP can also be used.
-
Java
-
XML
-
YAML
from("direct:search")
.to("elasticsearch://elasticsearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000")
.split(body()).streaming()
.to("mock:output")
.end(); <route>
<from uri="direct:search"/>
<to uri="elasticsearch://elasticsearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000"/>
<split streaming="true">
<simple>${body}</simple>
<to uri="mock:output"/>
</split>
</route> - route:
from:
uri: direct:search
steps:
- to:
uri: elasticsearch://elasticsearch
parameters:
operation: Search
indexName: twitter
useScroll: true
scrollKeepAliveMs: 30000
- split:
expression:
simple:
expression: "${body}"
streaming: true
steps:
- to:
uri: mock:output MultiSearch Example
MultiSearching on specific field(s) and value uses the Operation ´MultiSearch´. Pass in the MultiSearchRequest instance
-
Java
-
XML
-
YAML
from("direct:multiSearch")
.to("elasticsearch://elasticsearch?operation=MultiSearch"); <route>
<from uri="direct:multiSearch"/>
<to uri="elasticsearch://elasticsearch?operation=MultiSearch"/>
</route> - route:
from:
uri: direct:multiSearch
steps:
- to:
uri: elasticsearch://elasticsearch
parameters:
operation: MultiSearch MultiSearch on specific field(s)
MsearchRequest buildersMsearchRequest.Builder builder = new MsearchRequest.Builder().index("twitter").searches(
new RequestItem.Builder().header(new MultisearchHeader.Builder().build())
.body(new MultisearchBody.Builder().query(b -> b.matchAll(x -> x)).build()).build(),
new RequestItem.Builder().header(new MultisearchHeader.Builder().build())
.body(new MultisearchBody.Builder().query(b -> b.matchAll(x -> x)).build()).build());
List<MultiSearchResponseItem<?>> response = template.requestBody("direct:multiSearch", builder, List.class);