OpenSearch
Since Camel 4.0
Only producer is supported
The OpenSearch component allows you to interface with an OpenSearch 3.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-opensearch</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 OpenSearch 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 or openSearchClient option is set. | 30000 | int | |
The comma-separated list of the nodes to connect to, each as host:port, for example os1:9200,os2:9200. The port is 9200 if not set, and the scheme is https when enableSSL is set. Required unless the client or openSearchClient 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 or openSearchClient 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.opensearch.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. The openSearchClient option takes precedence over it. | RestClient | ||
Whether to start the Sniffer of the OpenSearch 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 or openSearchClient option is set. | false | boolean | |
Autowired To use an existing org.opensearch.client.opensearch.OpenSearchClient, shared by all the endpoints of the component that do not set their own, instead of a client that each producer creates. It takes precedence over the client option. The hostAddresses, timeout, authentication, SSL, sniffer and disconnect options are then not used, and the producers do not close the client. | OpenSearchClient | ||
The delay in milliseconds of the read of the nodes that the Sniffer schedules after a failed request. The component does not register the client listener that reports failures to the Sniffer, so this option has no effect. | 60000 | int | |
The interval in milliseconds between two reads of the nodes of the cluster, when enableSniffer is set. It must be greater than 0. | 300000 | int | |
API key to authenticate with, sent in the Authorization header instead of a user and password: the token OpenSearch returns when the key is created (it starts with os_), as is. API keys need OpenSearch 3.7 or newer. The key is only sent to the configured hosts and the nodes found by the sniffer. Not used when the client or openSearchClient option is set. | 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 the certificatePath option of the endpoint, is set. | false | boolean | |
The password for HTTP basic authentication to the nodes, used only together with user. Not used when the client or openSearchClient 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 the certificatePath option of the endpoint, 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 or openSearchClient option is set. | String |
Endpoint Options
The OpenSearch endpoint is configured using URI syntax:
opensearch: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 or the openSearchClient option is set. | 30000 | int | |
Whether the producer creates the client for each exchange and closes it when the exchange is done, instead of keeping one client from its start to its stop. Not used when the client option of the component or the openSearchClient option is set. | 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 CamelOpensearchFrom header replaces this option. | Integer | ||
The comma-separated list of the nodes to connect to, each as host:port, for example os1:9200,os2: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 or the openSearchClient option 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 CamelOpensearchIndexName header replaces this option, and a request of the OpenSearch Java 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 CamelOpensearchOperation header replaces this option. A request of the OpenSearch Java client in the body, such as an IndexRequest or a SearchRequest, sets the operation by its type and replaces both. Enum values:
| OpensearchOperation | ||
The time in milliseconds that OpenSearch keeps the search context of a scroll alive between two scroll requests, when useScroll is set. The CamelOpensearchScrollKeepAliveMs 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 CamelOpensearchSize 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 or the openSearchClient option is set. | 30000 | int | |
Whether Search reads all the hits with the scroll API. The body is then an OpensearchScrollRequestIterator of the hits, which sends the scroll requests while it is read and is to be closed after use. The CamelOpensearchUseScroll 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 CamelOpensearchWaitForActiveShards 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 use when deserializing the documents. | ObjectNode | Class | |
Whether to start the Sniffer of the OpenSearch 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 or the openSearchClient option is set. | false | boolean | |
The HostnameVerifier to use for the HTTPS connections, when enableSSL is set. By default none is set, and the HTTP client checks the host name itself. | HostnameVerifier | ||
Autowired To use an existing org.opensearch.client.opensearch.OpenSearchClient for this endpoint. It takes precedence over the client and openSearchClient options of the component. The hostAddresses, timeout, SSL, sniffer and disconnect options are then not used. The application is responsible for closing the client. | OpenSearchClient | ||
The delay in milliseconds of the read of the nodes that the Sniffer schedules after a failed request. The component does not register the client listener that reports failures to the Sniffer, so this option has no effect. | 60000 | int | |
The interval in milliseconds between two reads of the nodes of the cluster, when enableSniffer is set. It must be greater than 0. | 300000 | int | |
The CA certificate, in X.509 format, that the client trusts for the HTTPS connections to the OpenSearch cluster. 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 OpenSearch component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelOpensearchOperation (producer) Constant: | The operation that the producer performs. It replaces the operation option. A request of the OpenSearch Java client in the body sets the operation by its type and replaces both. Enum values:
| OpensearchOperation | |
CamelOpensearchIndexId (producer) Constant: | The id of the document for Index and Update. If it is not set for Index, OpenSearch generates the id. | String | |
CamelOpensearchIndexName (producer) Constant: | The name of the index that the operation acts on. It replaces the indexName option. | String | |
CamelOpensearchDocumentClass (producer) Constant: | The fully qualified name of the class of the document to unmarshal. | ObjectNode | Class |
CamelOpensearchWaitForActiveShards (producer) Constant: | The number of active shard copies that Index and Update wait for before they write. It replaces the waitForActiveShards option. | Integer | |
CamelOpensearchScrollKeepAliveMs (producer) Constant: | The time in milliseconds that OpenSearch keeps the search context of a scroll alive between two scroll requests. It replaces the scrollKeepAliveMs option. | Integer | |
CamelOpensearchUseScroll (producer) Constant: | Whether Search reads all the hits with the scroll API. It replaces the useScroll option. The body is then an OpensearchScrollRequestIterator of the hits, to be closed after use. | Boolean | |
CamelOpensearchSize (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 | |
CamelOpensearchFrom (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 |
Message Body
The message body at each side of the OpenSearch 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 CamelOpensearchOperation header, or by the request of the OpenSearch 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 takes the partial document, or the Update API form {"doc": {…}}. 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 CamelOpensearchIndexName header nor indexName is set. Each also takes its request of the OpenSearch 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 OpenSearch client (found() is false for no document), Search the HitsMetadata of the hits, or with useScroll an OpensearchScrollRequestIterator 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.
Usage
Message Operations
The following OpenSearch 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 OpenSearch 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 |
|---|---|---|
|
| 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". |
|
| Retrieves the document corresponding to the given index id and returns a GetResponse object in the body. You can set the name of the target index by setting the message header with the key "indexName". You can set the type of document by setting the message header with the key "documentClass". |
|
| Deletes the document with the given id 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". |
|
| Deletes the index named by the indexName header or option, or else the one named by a |
|
| 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 the content with the search request as a JSON |
|
| Multiple search in one |
|
| Multiple get in one You can set the name of the target index by setting the message header with the key "indexName". |
| None | Checks 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". |
|
| 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". |
Ping | None | Pings the OpenSearch cluster and returns true if the ping succeeded, false otherwise |
Configure the component and enable basic authentication
To use the OpenSearch component, it has to be configured with a minimum configuration.
OpensearchComponent opensearchComponent = new OpensearchComponent();
opensearchComponent.setHostAddresses("opensearch-host:9200");
camelContext.addComponent("opensearch", opensearchComponent); For basic authentication with OpenSearch or using reverse http proxy in front of the OpenSearch cluster, simply setup basic authentication and SSL on the component like the example below
OpensearchComponent opensearchComponent = new OpensearchComponent();
opensearchComponent.setHostAddresses("opensearch-host:9200");
opensearchComponent.setUser("opensearchuser");
opensearchComponent.setPassword("secure!!");
camelContext.addComponent("opensearch", opensearchComponent); Authenticate with an API key
Since OpenSearch 3.7, the Security plugin has API keys. Instead of a user and password, the component can log in with one: set the apiKey option to the token OpenSearch returns when the key is created (it starts with os_). Camel sends it as the Authorization: ApiKey … header.
camel.component.opensearch.host-addresses=myopensearchhost:9200
camel.component.opensearch.enable-ssl=true
camel.component.opensearch.api-key={{opensearch.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 or openSearchClient option, the apiKey option is not used, as for user and password.
A key to index documents needs the indices:data/write/bulk cluster permission, besides its index permissions: OpenSearch runs the index of a single document as a bulk request. |
Custom clients per endpoint
Use the openSearchClient endpoint option to reference an org.opensearch.client.opensearch.OpenSearchClient in the Camel registry. Each endpoint can use a different client, allowing a single route to connect to different OpenSearch services with their own authentication and transport settings.
camelContext.getRegistry().bind("firstClient", firstClient);
camelContext.getRegistry().bind("secondClient", secondClient);
from("direct:ping")
.to("opensearch:first?operation=Ping&openSearchClient=#bean:firstClient")
.to("opensearch:second?operation=Ping&openSearchClient=#bean:secondClient"); The endpoint client takes precedence over the component’s openSearchClient and client options. Without an endpoint override, the component’s client configuration continues to apply. Configure connection and authentication settings on the supplied client; hostAddresses is not required when supplying a client.
The application owns supplied clients and must close them when they are no longer needed. Camel does not close them when a route stops or when disconnect=true.
Examples
Index Example
Below is a simple INDEX example
-
Java
-
XML
-
YAML
from("direct:index")
.to("opensearch://opensearch?operation=Index&indexName=twitter"); <route>
<from uri="direct:index"/>
<to uri="opensearch://opensearch?operation=Index&indexName=twitter"/>
</route> - route:
from:
uri: direct:index
steps:
- to:
uri: opensearch://opensearch
parameters:
operation: Index
indexName: twitter The indexId header (CamelOpensearchIndexId) 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("opensearch://opensearch?operation=Search&indexName=twitter"); <route>
<from uri="direct:search"/>
<to uri="opensearch://opensearch?operation=Search&indexName=twitter"/>
</route> - route:
from:
uri: direct:search
steps:
- to:
uri: opensearch://opensearch
parameters:
operation: Search
indexName: twitter String query = "{\"query\":{\"match\":{\"doc.content\":\"new release of ApacheCamel\"}},\"size\":5}";
HitsMetadata<?> response = template.requestBody("direct:search", query, HitsMetadata.class); Search on specific field(s) using Map.
Map<String, Object> actualQuery = new HashMap<>();
actualQuery.put("doc.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 OpenSearch scroll api to fetch all results.
-
Java
-
XML
-
YAML
from("direct:search")
.to("opensearch://opensearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000"); <route>
<from uri="direct:search"/>
<to uri="opensearch://opensearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000"/>
</route> - route:
from:
uri: direct:search
steps:
- to:
uri: opensearch://opensearch
parameters:
operation: Search
indexName: twitter
useScroll: true
scrollKeepAliveMs: 30000 String query = "{\"query\":{\"match\":{\"doc.content\":\"new release of ApacheCamel\"}}}";
try (OpensearchScrollRequestIterator response = template.requestBody("direct:search", query, OpensearchScrollRequestIterator.class)) {
// do something smart with results
} Split EIP can also be used.
-
Java
-
XML
-
YAML
from("direct:search")
.to("opensearch://opensearch?operation=Search&indexName=twitter&useScroll=true&scrollKeepAliveMs=30000")
.split()
.body()
.streaming()
.to("mock:output")
.end(); <route>
<from uri="direct:search"/>
<to uri="opensearch://opensearch?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: opensearch://opensearch
parameters:
operation: Search
indexName: twitter
useScroll: true
scrollKeepAliveMs: 30000
- split:
simple: "${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("opensearch://opensearch?operation=MultiSearch"); <route>
<from uri="direct:multiSearch"/>
<to uri="opensearch://opensearch?operation=MultiSearch"/>
</route> - route:
from:
uri: direct:multiSearch
steps:
- to:
uri: opensearch://opensearch
parameters:
operation: MultiSearch MultiSearch on specific field(s)
MsearchRequest.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); Custom OpenSearchClient Example
You can provide a pre-configured OpenSearchClient instance instead of letting the component build one from host addresses. This is useful when you need a custom transport, for example when connecting to AWS OpenSearch Service with IAM-based authentication.
// Build a custom OpenSearchClient (e.g., with AWS SDK transport)
OpenSearchClient customClient = new OpenSearchClient(myCustomTransport);
// Bind it to the registry so it can be autowired
context.getRegistry().bind("myOpenSearchClient", customClient); The component will automatically pick up the OpenSearchClient from the registry via autowiring. When both a RestClient and an OpenSearchClient are available, the OpenSearchClient takes precedence.