Full Elasticsearch 8.x Java API Client Code Ready for Immediate Project Use

This article walks through the new features of the Elasticsearch 8.x Java API client, shows how to set up the development environment, initialize the client with HTTPS or API‑key authentication, and provides complete, ready‑to‑run code examples for index creation, document indexing, searching, aggregations, and scripted sorting.

Mingyi World Elasticsearch
Mingyi World Elasticsearch
Mingyi World Elasticsearch
Full Elasticsearch 8.x Java API Client Code Ready for Immediate Project Use

Features of the Elasticsearch 8.x Java API Client

Strongly‑typed requests and responses

Provides type‑safe request and response objects for all Elasticsearch APIs, reducing runtime errors.

Enables IDE auto‑completion and improved developer productivity.

Synchronous and asynchronous APIs

Synchronous calls execute sequentially, guaranteeing order of operations.

Asynchronous calls are non‑blocking, suitable for high‑concurrency or latency‑sensitive scenarios.

Fluent builders and functional programming

Fluent, chainable builders allow concise construction of complex requests.

Lambda expressions simplify code and improve readability.

Object mapper integration

Jackson is the default JSON mapper, enabling direct conversion between Java objects and JSON.

Any JSON‑B‑compatible library can be used as an alternative.

Protocol handling via the low‑level REST client

HTTP connection pooling, retry mechanisms, and node discovery are delegated to the low‑level REST client.

Developers can focus on business logic without managing low‑level details.

Environment preparation

Ensure Elasticsearch 8.x is running and the development environment includes:

JDK 1.8 or higher

Elasticsearch Java API Client dependency

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mingyi.cn</groupId>
  <artifactId>ESJavaClient</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>co.elastic.clients</groupId>
      <artifactId>elasticsearch-java</artifactId>
      <version>8.11.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.3</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
    </dependency>
  </dependencies>
</project>

Elasticsearch client initialization

HTTPS‑based initialization (default security)

Steps:

Configure a CredentialsProvider with username/password.

Load the CA certificate provided by Elasticsearch.

Create an SSLContext using the loaded certificate.

Build a low‑level RestClient with the SSL context and credentials.

Wrap the RestClient in a RestClientTransport using JacksonJsonpMapper.

Instantiate ElasticsearchClient with the transport.

// Set username and password
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
    new UsernamePasswordCredentials("elastic", "your_password"));

// Load CA certificate
Path caCertificatePath = Paths.get("path/to/http_ca.crt");
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate trustedCa;
try (InputStream is = Files.newInputStream(caCertificatePath)) {
    trustedCa = factory.generateCertificate(is);
}

// Configure SSL context
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", trustedCa);
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
    .loadTrustMaterial(trustStore, null);
final SSLContext sslContext = sslContextBuilder.build();

// Build RestClient
RestClientBuilder builder = RestClient.builder(
    new HttpHost("localhost", 9200, "https"))
    .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
        .setSSLContext(sslContext)
        .setDefaultCredentialsProvider(credentialsProvider)
        .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE));

RestClient restClient = builder.build();

// Create Elasticsearch client
ElasticsearchTransport transport = new RestClientTransport(
    restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);

API‑Key based initialization (optional)

String apiKeyId = "your_api_key_id";
String apiKeySecret = "your_api_key_secret";
String apiKeyAuth = Base64.getEncoder().encodeToString(
    (apiKeyId + ":" + apiKeySecret).getBytes(StandardCharsets.UTF_8));
Header[] defaultHeaders = {
    new BasicHeader("Authorization", "ApiKey " + apiKeyAuth)
};
builder.setDefaultHeaders(defaultHeaders);

Basic operation examples

Create index

public void createIndex(String indexName) throws IOException {
    client.indices().create(c -> c.index(indexName));
}

Index document

public void indexDocument(String indexName, String id, Map<String, Object> document) throws IOException {
    client.index(i -> i.index(indexName).id(id).document(document));
}

Search documents

public SearchResponse<Object> search(String indexName, List<Query> queries, List<SortOptions> sortOptions, int page, int pageSize) throws IOException {
    SearchRequest.Builder builder = new SearchRequest.Builder()
        .index(indexName)
        .from(page * pageSize)
        .size(pageSize)
        .query(q -> q.bool(b -> b.must(queries)));
    if (sortOptions != null && !sortOptions.isEmpty()) {
        builder.sort(sortOptions);
    }
    return client.search(builder.build(), Object.class);
}

Aggregation query

public SearchResponse<Object> aggregateSearch(String indexName, List<Query> queries, Map<String, Aggregation> aggregations) throws IOException {
    return client.search(s -> s
        .index(indexName)
        .query(q -> q.bool(b -> b.must(queries)))
        .aggregations(aggregations), Object.class);
}

Scripted sort example

public SearchResponse<Map> searchWithScriptSort(String indexName, String fieldName, String queryText, String scriptSource, double factor) throws IOException {
    Query query = MatchQuery.of(m -> m.field(fieldName).query(queryText))._toQuery();
    Script script = Script.of(s -> s.inline(i -> i
        .source(scriptSource)
        .params("factor", JsonData.of(factor))));
    SortOptions sortOptions = SortOptions.of(so -> so.script(ss -> ss
        .script(script)
        .type(ScriptSortType.Number)
        .order(SortOrder.Asc)));
    SearchRequest request = new SearchRequest.Builder()
        .index(indexName)
        .query(query)
        .sort(sortOptions)
        .build();
    return client.search(request, Map.class);
}

Full code example

public class ElasticsearchService {
    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchService.class);
    private ElasticsearchClient client;

    // Constructor – initialize client (HTTPS or API‑Key)
    public ElasticsearchService() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        // Initialization logic from the HTTPS example above
    }

    public void createIndex(String indexName) throws IOException {
        client.indices().create(c -> c.index(indexName));
    }

    public void indexDocument(String indexName, String id, Map<String, Object> document) throws IOException {
        client.index(i -> i.index(indexName).id(id).document(document));
    }

    public SearchResponse<Object> search(String indexName, List<Query> queries, List<SortOptions> sortOptions, int page, int pageSize) throws IOException {
        // Implementation from the search example
    }

    public SearchResponse<Object> aggregateSearch(String indexName, List<Query> queries, Map<String, Aggregation> aggs) throws IOException {
        // Implementation from the aggregation example
    }

    public SearchResponse<Map> searchWithScriptSort(String indexName, String fieldName, String queryText, String scriptSource, double factor) throws IOException {
        // Implementation from the scripted sort example
    }

    public static void main(String[] args) {
        try {
            ElasticsearchService service = new ElasticsearchService();
            String index = "my-index";
            service.createIndex(index);
            Map<String, Object> doc = new HashMap<>();
            doc.put("title", "Elasticsearch Basics");
            doc.put("author", "John Doe");
            doc.put("content", "This is a tutorial for Elasticsearch.");
            service.indexDocument(index, "1", doc);
            service.client.indices().refresh(r -> r.index(index));

            Query q = QueryBuilders.match(m -> m.field("title").query("Elasticsearch"));
            List<Query> queries = Arrays.asList(q);
            SearchResponse<Object> resp = service.search(index, queries, null, 0, 10);
            resp.hits().hits().forEach(hit -> logger.info(hit.source().toString()));

            Aggregation agg = AggregationBuilders.terms(t -> t.field("author.keyword"));
            Map<String, Aggregation> aggMap = new HashMap<>();
            aggMap.put("author_count", agg);
            SearchResponse<Object> aggResp = service.aggregateSearch(index, queries, aggMap);
            aggResp.aggregations().forEach((k, a) -> logger.info(k + ": " + a));

            String script = "doc['content.keyword'].value.length() * params.factor";
            SearchResponse<Map> scriptResp = service.searchWithScriptSort(index, "content", "Elasticsearch", script, 1.1);
            scriptResp.hits().hits().forEach(hit -> logger.info(hit.source().toString()));
        } catch (Exception e) {
            logger.error("Error occurred:", e);
        }
    }
}

Important notes

Authentication

Elasticsearch 8.x enables security by default; choose between username/password or API‑key authentication based on the deployment scenario.

SSL certificates

Load the CA certificate supplied by Elasticsearch to establish a trusted SSL connection.

Dependency versions

Ensure the Elasticsearch Java API Client version matches the Elasticsearch server version.

References

Elasticsearch Java API Client official documentation – https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/index.html

Elasticsearch security communication configuration – http://mp.weixin.qq.com/s?__biz=MzI2NDY1MTA3OQ==∣=2247490205&idx=1&sn=d53abd874b9ef1a55946a5ccccf1ff5a&scene=21#wechat_redirect

Elasticsearch aggregation queries – http://mp.weixin.qq.com/s?__biz=MzI2NDY1MTA3OQ==∣=2247485927&idx=1&sn=23f46f436890627523abfbc6f65cda1d&scene=21#wechat_redirect

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaElasticsearchSearchElasticsearch 8.xJava API Client
Mingyi World Elasticsearch
Written by

Mingyi World Elasticsearch

The leading WeChat public account for Elasticsearch fundamentals, advanced topics, and hands‑on practice. Join us to dive deep into the ELK Stack (Elasticsearch, Logstash, Kibana, Beats).

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.