Automatic Index Creation in Elasticsearch with Java

When you need an Elasticsearch index to appear the moment your application starts, the Java High Level REST Client can do the heavy lifting. Below is a concise walk-through that shows how to bootstrap an index, define its mapping, and make it searchable without ever touching Kibana.

Overview

Stage What happens
1 Open a TCP connection to the cluster
2 Describe the index structure (settings + mapping)
3 Send the definition to the cluster
4 Verify the index exists and is ready

1. Opening the connection

RestHighLevelClient es = new RestHighLevelClient(
        RestClient.builder(
            new HttpHost("127.0.0.1", 9200, "http")
        )
);

2. Describing the index

Elasticsearch accepts JSON for every thing. The snippet below creates a tiny mapping for a "product" index with two fields.

String mapping = """
{
  "mappings": {
    "properties": {
      "sku":   { "type": "keyword" },
      "price": { "type": "double"  }
    }
  }
}
""";

3. Sending the definition

CreateIndexRequest request = new CreateIndexRequest("product")
        .source(mapping, XContentType.JSON);

CreateIndexResponse resp = es.indices().create(request, RequestOptions.DEFAULT);
if (resp.isAcknowledged()) {
    System.out.println("Index created");
}

4. Verifying readiness

boolean ready = es.indices()
                   .exists(new GetIndexRequest("product"), RequestOptions.DEFAULT);
System.out.println("Index exists? " + ready);

Comlpete runnable snippet

import org.apache.http.HttpHost;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.*;

public class AutoIndexCreator {
    public static void main(String[] args) throws Exception {
        try (RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")))) {

            String mapping = """
            {
              "mappings": {
                "properties": {
                  "sku":   { "type": "keyword" },
                  "price": { "type": "double"  }
                }
              }
            }
            """;

            CreateIndexRequest req = new CreateIndexRequest("product")
                    .source(mapping, XContentType.JSON);

            CreateIndexResponse resp = client.indices().create(req, RequestOptions.DEFAULT);
            System.out.println("Acknowledged = " + resp.isAcknowledged());
        }
    }
}

Tags: elasticsearch Java High Level REST Client CreateIndexRequest index mapping RestHighLevelClient

Posted on Thu, 05 Nov 2026 16:44:11 +0000 by Mantis_61