Camel Components

Elasticsearch Low level Rest Client

Since Camel 4.3

Only producer is supported

The ElasticSearch component allows you to interface with ElasticSearch 8.x API or OpenSearch using the ElasticSearch Java Low level Rest Client.

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-rest-client</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

elasticsearch-rest-client://clusterName[?options]

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 Elasticsearch Low level Rest Client component supports the following options which are listed below.

Name Description Default Type

connectionTimeout (producer)

The connect timeout in milliseconds: the longest time that the client waits to establish the connection to a node. Zero means no timeout. Not used when the restClient option is set.

30000

int

hostAddressesList (producer)

The comma-separated list of the nodes to connect to, each as [scheme://]host[:port], for example http://es1:9200,http://es2:9200. The scheme is http if not set, and the port is the default port of the scheme (80 for http, 443 for https) if not set. Required unless the restClient option is set.

String

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

socketTimeout (producer)

The socket timeout in milliseconds: the longest time that the client waits for data from a node before the request fails. Zero means no timeout. Not used when the restClient option is set.

30000

int

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

enableSniffer (advanced)

Whether to start the Sniffer of the Elasticsearch REST client, which reads the nodes of the cluster from its Nodes Info API at start and then at the snifferInterval, and updates the nodes that the client sends requests to. Not used when the restClient option is set.

false

boolean

restClient (advanced)

Autowired The org.elasticsearch.client.RestClient to use, instead of a client that the producer creates. When set, hostAddressesList and the timeout, security and sniffer options are not used, and the producer does not close the client when it stops.

RestClient

sniffAfterFailureDelay (advanced)

The delay in milliseconds of the read of the nodes that the Sniffer schedules after a failed request, when enableSniffer is set. Must be greater than 0. It has no effect at the moment, as the client is created without the listener that reports failed requests to the Sniffer. The Sniffer then reads the nodes only at the snifferInterval.

60000

int

snifferInterval (advanced)

The interval in milliseconds between two reads of the nodes of the cluster, when enableSniffer is set. Must be greater than 0.

60000

int

certificatePath (security)

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:. sslContextParameters takes precedence.

String

password (security)

The password for basic authentication. Used only when user is also set.

String

sslContextParameters (security)

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.

SSLContextParameters

useGlobalSslContextParameters (security)

Enable usage of global SSL context parameters.

false

boolean

user (security)

The user name for basic authentication. Used only when password is also set.

String

Endpoint Options

The Elasticsearch Low level Rest Client endpoint is configured using URI syntax:

elasticsearch-rest-client:clusterName

With the following path and query parameters:

Path Parameters

Name Description Default Type

clusterName (producer)

Required The name of the Elasticsearch cluster. It only names the endpoint: the hostAddressesList option or the restClient option sets the nodes to connect to.

String

Query Parameters

Name Description Default Type

connectionTimeout (producer)

The connect timeout in milliseconds: the longest time that the client waits to establish the connection to a node. Zero means no timeout. Not used when the restClient option is set.

30000

int

hostAddressesList (producer)

The comma-separated list of the nodes to connect to, each as [scheme://]host[:port], for example http://es1:9200,http://es2:9200. The scheme is http if not set, and the port is the default port of the scheme (80 for http, 443 for https) if not set. Required unless the restClient option is set.

String

indexName (producer)

The name of the index that the operation acts on. When not set, the CamelElasticsearchIndexName header is used. Either the option or the header is required.

String

operation (producer)

The operation that the producer performs. The CamelElasticsearchOperation header replaces this option. Either the option or the header is required.

Enum values:

  • INDEX_OR_UPDATE

  • GET_BY_ID

  • DELETE

  • CREATE_INDEX

  • DELETE_INDEX

  • SEARCH

ElasticsearchRestClientOperation

socketTimeout (producer)

The socket timeout in milliseconds: the longest time that the client waits for data from a node before the request fails. Zero means no timeout. Not used when the restClient option is set.

30000

int

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

enableSniffer (advanced)

Whether to start the Sniffer of the Elasticsearch REST client, which reads the nodes of the cluster from its Nodes Info API at start and then at the snifferInterval, and updates the nodes that the client sends requests to. Not used when the restClient option is set.

false

boolean

restClient (advanced)

Autowired The org.elasticsearch.client.RestClient to use, instead of a client that the producer creates. When set, hostAddressesList and the timeout, security and sniffer options are not used, and the producer does not close the client when it stops.

RestClient

sniffAfterFailureDelay (advanced)

The delay in milliseconds of the read of the nodes that the Sniffer schedules after a failed request, when enableSniffer is set. Must be greater than 0. It has no effect at the moment, as the client is created without the listener that reports failed requests to the Sniffer. The Sniffer then reads the nodes only at the snifferInterval.

60000

int

snifferInterval (advanced)

The interval in milliseconds between two reads of the nodes of the cluster, when enableSniffer is set. Must be greater than 0.

60000

int

certificatePath (security)

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:. sslContextParameters takes precedence.

String

password (security)

The password for basic authentication. Used only when user is also set.

String

sslContextParameters (security)

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.

SSLContextParameters

user (security)

The user name for basic authentication. Used only when password is also set.

String

Message Headers

The Elasticsearch Low level Rest Client component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelElasticsearchId (producer)

Constant: ID

The id of the document to index, get or delete. INDEX_OR_UPDATE indexes the body under this id, or under an id that Elasticsearch generates when not set. GET_BY_ID and DELETE use the body as the id when this header is not set.

String

CamelElasticsearchSearchQuery (producer)

Constant: SEARCH_QUERY

The JSON query of the SEARCH operation. When not set, the body is used.

String

CamelElasticsearchIndexSettings (producer)

Constant: INDEX_SETTINGS

The JSON body of the CREATE_INDEX request, with the settings, mappings or aliases of the new index.

String

CamelElasticsearchIndexName (producer)

Constant: INDEX_NAME

The name of the index that the operation acts on, used when the indexName option is not set.

String

CamelElasticsearchOperation (producer)

Constant: OPERATION

The operation to perform. It replaces the operation option.

Enum values:

  • INDEX_OR_UPDATE

  • GET_BY_ID

  • DELETE

  • CREATE_INDEX

  • DELETE_INDEX

  • SEARCH

ElasticsearchRestClientOperation

Message Body

The message body at each side of the Elasticsearch Low level Rest Client 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, value, map or null

By the operation, set by the operation option or the CamelElasticsearchOperation header. INDEX_OR_UPDATE sends the body as the JSON document: text, bytes, a stream or a file of it; a Map or a POJO is sent as its toString() and fails, so marshal it to JSON first. GET_BY_ID and DELETE take the id of the CamelElasticsearchId header, or else the body. SEARCH takes the JSON query of the CamelElasticsearchSearchQuery header, or else the body: a Map of field names and values to match, or the JSON query as text, bytes, a stream or a file; with no body all documents match. CREATE_INDEX and DELETE_INDEX do not use the body: the settings of a new index are in the CamelElasticsearchIndexSettings header.

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

  • With operation=GET_BY_ID: text, value or null

  • With operation=DELETE: text, value or null

  • With operation=SEARCH: text, bytes, stream, file, map or null

  • With operation=CREATE_INDEX: any

  • With operation=DELETE_INDEX: any

Producer output

text or value

The id of the document as text for INDEX_OR_UPDATE. GET_BY_ID gives the source of the document as JSON text, and SEARCH a JSON array of the sources of the hits as text: unmarshal them to read their fields. DELETE, CREATE_INDEX and DELETE_INDEX give true. A missing id or index, or an index that is already there, fails with the error of the server: a GET_BY_ID of a missing id fails with 404 rather than giving null.

  • With operation=INDEX_OR_UPDATE: text (java.lang.String)

  • With operation=GET_BY_ID: text (java.lang.String)

  • With operation=SEARCH: text (java.lang.String)

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

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

  • With operation=DELETE_INDEX: 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.

Elasticsearch Low level Rest Client Operations

Set an endpoint URI option or exchange header with a name of operation and a value of one of the following supported options.

operation message body description

INDEX_OR_UPDATE

String, byte[], Reader or InputStream content to index or update

Adds or updates content to an index and returns the resulting id in the message body. You can set the name of the target index from the indexName URI parameter option, or by providing a message header with the key CamelElasticsearchIndexName. When updating indexed content, you must provide its id via a message header with the key CamelElasticsearchId.

GET_BY_ID

String id of content to retrieve

Retrieves a JSON String representation of the indexed document, corresponding to the given index id and sets it as the message exchange body. You can set the name of the target index from the indexName URI parameter option, or by providing a message header with the key CamelElasticsearchIndexName. You must provide the index id of the content to retrieve either via a message header with the key CamelElasticsearchId, or in the message body: the header wins over the body. A missing id fails with the error of the server (404).

DELETE

String id of content to delete

Deletes the document with the given id from the index and returns a boolean value as the message exchange body, indicating whether the operation was successful. You can set the name of the target index from the indexName URI parameter option, or by providing a message header with the key CamelElasticsearchIndexName. You must provide the index id of the content to delete either via a message header with the key CamelElasticsearchId, or in the message body: the header wins over the body.

CREATE_INDEX

Creates the specified indexName and returns a boolean value as the message exchange body, indicating whether the operation was successful. You can set the name of the target index to create from the indexName URI parameter option, or by providing a message header with the key CamelElasticsearchIndexName. You may also provide a header with the key CamelElasticsearchIndexSettings where the value is a JSON String representation of the index settings.

DELETE_INDEX

Deletes the specified indexName and returns a boolean value as the message exchange body, indicating whether the operation was successful. You can set the name of the target index to delete from the indexName URI parameter option, or by providing a message header with the key CamelElasticsearchIndexName.

SEARCH

Map or JSON String (optional)

Search for content with either a Map of String keys & values of query criteria in the body, a JSON string representation of the query in the body, or one in the CamelElasticsearchSearchQuery header, which wins over the body. With no body and no header, all documents match. Matching documents are returned as a JSON array string of their sources set on the message exchange body. You can set the JSON query String by providing a message header with the key CamelElasticsearchSearchQuery, or as the message body. You can set the message exchange body to a Map of String keys & values for the query criteria.

The document id and the index name are each sent as one path segment of the request, with reserved characters such as /, ?, , % and spaces percent-encoded, so Elasticsearch takes them literally. A document id of . or .. is rejected, as is an index name that contains a character Elasticsearch does not allow in an index name (\, /, ?, ", <, >, |, or a space). A comma separated list of index names and patterns, such as logs-*,my_index, can be used to search several indexes.

Examples

Index Content Example

To index some content.

  • Java

  • XML

  • YAML

from("direct:index")
    .setBody().constant("{\"content\": \"ElasticSearch With Camel\"}")
    .to("elasticsearch-rest-client://myCluster?operation=INDEX_OR_UPDATE&indexName=myIndex");
<route>
  <from uri="direct:index"/>
  <setBody>
    <constant>{"content": "ElasticSearch With Camel"}</constant>
  </setBody>
  <to uri="elasticsearch-rest-client://myCluster?operation=INDEX_OR_UPDATE&amp;indexName=myIndex"/>
</route>
- route:
    from:
      uri: direct:index
      steps:
        - setBody:
            constant: '{"content": "ElasticSearch With Camel"}'
        - to:
            uri: elasticsearch-rest-client://myCluster
            parameters:
              operation: INDEX_OR_UPDATE
              indexName: myIndex

To update existing indexed content, provide the CamelElasticsearchId message header and the message body with the updated content.

  • Java

  • XML

  • YAML

from("direct:index")
    .setHeader("CamelElasticsearchId").constant("1")
    .setBody().constant("{\"content\": \"ElasticSearch REST Client With Camel\"}")
    .to("elasticsearch-rest-client://myCluster?operation=INDEX_OR_UPDATE&indexName=myIndex");
<route>
  <from uri="direct:index"/>
  <setHeader name="CamelElasticsearchId">
    <constant>1</constant>
  </setHeader>
  <setBody>
    <constant>{"content": "ElasticSearch REST Client With Camel"}</constant>
  </setBody>
  <to uri="elasticsearch-rest-client://myCluster?operation=INDEX_OR_UPDATE&amp;indexName=myIndex"/>
</route>
- route:
    from:
      uri: direct:index
      steps:
        - setHeader:
            name: CamelElasticsearchId
            constant: "1"
        - setBody:
            constant: '{"content": "ElasticSearch REST Client With Camel"}'
        - to:
            uri: elasticsearch-rest-client://myCluster
            parameters:
              operation: INDEX_OR_UPDATE
              indexName: myIndex

Get By ID Example

  • Java

  • XML

  • YAML

from("direct:getById")
    .setHeader("CamelElasticsearchId").constant("1")
    .to("elasticsearch-rest-client://myCluster?operation=GET_BY_ID&indexName=myIndex");
<route>
  <from uri="direct:getById"/>
  <setHeader name="CamelElasticsearchId">
    <constant>1</constant>
  </setHeader>
  <to uri="elasticsearch-rest-client://myCluster?operation=GET_BY_ID&amp;indexName=myIndex"/>
</route>
- route:
    from:
      uri: direct:getById
      steps:
        - setHeader:
            name: CamelElasticsearchId
            constant: "1"
        - to:
            uri: elasticsearch-rest-client://myCluster
            parameters:
              operation: GET_BY_ID
              indexName: myIndex

Delete Example

To delete indexed content, provide the CamelElasticsearchId message header.

  • Java

  • XML

  • YAML

from("direct:getById")
    .setHeader("CamelElasticsearchId").constant("1")
    .to("elasticsearch-rest-client://myCluster?operation=DELETE&indexName=myIndex");
<route>
  <from uri="direct:getById"/>
  <setHeader name="CamelElasticsearchId">
    <constant>1</constant>
  </setHeader>
  <to uri="elasticsearch-rest-client://myCluster?operation=DELETE&amp;indexName=myIndex"/>
</route>
- route:
    from:
      uri: direct:getById
      steps:
        - setHeader:
            name: CamelElasticsearchId
            constant: "1"
        - to:
            uri: elasticsearch-rest-client://myCluster
            parameters:
              operation: DELETE
              indexName: myIndex

Create Index Example

To create a new index.

  • Java

  • XML

  • YAML

from("direct:createIndex")
    .to("elasticsearch-rest-client://myCluster?operation=CREATE_INDEX&indexName=myIndex");
<route>
  <from uri="direct:createIndex"/>
  <to uri="elasticsearch-rest-client://myCluster?operation=CREATE_INDEX&amp;indexName=myIndex"/>
</route>
- route:
    from:
      uri: direct:createIndex
      steps:
        - to:
            uri: elasticsearch-rest-client://myCluster
            parameters:
              operation: CREATE_INDEX
              indexName: myIndex

To create a new index with some custom settings.

Java-only: uses a Java String variable for index settings
String indexSettings = "{\"settings\":{\"number_of_replicas\": 1,\"number_of_shards\": 3,\"analysis\": {},\"refresh_interval\": \"1s\"},\"mappings\":{\"dynamic\": false,\"properties\": {\"title\": {\"type\": \"text\", \"analyzer\": \"english\"}}}}";
Java-only: route using the indexSettings Java variable
from("direct:createIndex")
    .setHeader("CamelElasticsearchIndexSettings").constant(indexSettings)
    .to("elasticsearch-rest-client://myCluster?operation=CREATE_INDEX&indexName=myIndex");

Delete Index Example

To delete an index.

  • Java

  • XML

  • YAML

from("direct:deleteIndex")
    .to("elasticsearch-rest-client://myCluster?operation=DELETE_INDEX&indexName=myIndex");
<route>
  <from uri="direct:deleteIndex"/>
  <to uri="elasticsearch-rest-client://myCluster?operation=DELETE_INDEX&amp;indexName=myIndex"/>
</route>
- route:
    from:
      uri: direct:deleteIndex
      steps:
        - to:
            uri: elasticsearch-rest-client://myCluster
            parameters:
              operation: DELETE_INDEX
              indexName: myIndex

Search Example

Search with a JSON query.

  • Java

  • XML

  • YAML

from("direct:search")
    .setHeader("CamelElasticsearchSearchQuery").constant("{\"query\":{\"match\":{\"content\":\"ElasticSearch With Camel\"}}}")
    .to("elasticsearch-rest-client://myCluster?operation=SEARCH&indexName=myIndex");
<route>
  <from uri="direct:search"/>
  <setHeader name="CamelElasticsearchSearchQuery">
    <constant>{"query":{"match":{"content":"ElasticSearch With Camel"}}}</constant>
  </setHeader>
  <to uri="elasticsearch-rest-client://myCluster?operation=SEARCH&amp;indexName=myIndex"/>
</route>
- route:
    from:
      uri: direct:search
      steps:
        - setHeader:
            name: CamelElasticsearchSearchQuery
            constant: '{"query":{"match":{"content":"ElasticSearch With Camel"}}}'
        - to:
            uri: elasticsearch-rest-client://myCluster
            parameters:
              operation: SEARCH
              indexName: myIndex

The JSON query can also be the message body, when the CamelElasticsearchSearchQuery header is not set.

Java-only: ProducerTemplate with the JSON query as the body
String query = "{\"query\":{\"match\":{\"content\":\"ElasticSearch With Camel\"}}}";
String hits = template.requestBody("elasticsearch-rest-client://myCluster?operation=SEARCH&indexName=myIndex", query,
        String.class);

Search on specific field(s) using Map.

Java-only: creating a search criteria Map
Map<String, String> criteria = new HashMap<>();
criteria.put("content", "Camel");
Java-only: route using the criteria Java variable
from("direct:search")
    .setBody().constant(criteria)
    .to("elasticsearch-rest-client://myCluster?operation=SEARCH&indexName=myIndex");