Skip to content

Latest commit

 

History

History
84 lines (66 loc) · 2.32 KB

File metadata and controls

84 lines (66 loc) · 2.32 KB
endpoint _connection
lang java
es_version 9.3
client co.elastic.clients:elasticsearch-java:9.3.0

Elasticsearch 9.3 connection management (Java example)

Use ElasticsearchClient to create a client. The simplest approach uses basic authentication with a username and password:

import co.elastic.clients.elasticsearch.ElasticsearchClient;

var client = ElasticsearchClient.of(b -> b
    .host("http://localhost:9200")
    .usernameAndPassword("elastic", "your-password")
);

var info = client.info();
System.out.printf("Connected to %s (v%s)%n",
    info.clusterName(), info.version().number());

Add the dependency to your pom.xml:

<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>9.3.0</version>
</dependency>

API key authentication

For production use, API keys are preferred over username/password. Pass the base64-encoded API key directly:

var client = ElasticsearchClient.of(b -> b
    .host("http://localhost:9200")
    .apiKey("your-base64-api-key")
);

Connection options

For advanced configuration such as custom TLS settings or connection pooling, use the low-level RestClient transport:

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;

var credsProv = new BasicCredentialsProvider();
credsProv.setCredentials(AuthScope.ANY,
    new UsernamePasswordCredentials("elastic", "your-password"));

var restClient = RestClient.builder(HttpHost.create("https://my-cluster.example.com:9243"))
    .setHttpClientConfigCallback(b -> b.setDefaultCredentialsProvider(credsProv))
    .setRequestConfigCallback(b -> b.setSocketTimeout(30_000))
    .build();

var transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
var client = new ElasticsearchClient(transport);

To verify the connection is working:

if (client.ping().value()) {
    System.out.println("Connected");
} else {
    System.out.println("Connection failed");
}