Create Index API

Create Index Request

A CreateIndexRequest requires an index argument:

CreateIndexRequest request = new CreateIndexRequest("twitter"); 

The index to create

Index settings

Each index created can have specific settings associated with it.

request.settings(Settings.builder() 
    .put("index.number_of_shards", 3)
    .put("index.number_of_replicas", 2)
);

Settings for this index

Index mappings

An index may be created with mappings for its document types

request.mapping(
        "{\n" +
        "  \"properties\": {\n" +
        "    \"message\": {\n" +
        "      \"type\": \"text\"\n" +
        "    }\n" +
        "  }\n" +
        "}", 
        XContentType.JSON);

The type to define

The mapping for this type, provided as a JSON string

The mapping source can be provided in different ways in addition to the String example shown above:

Map<String, Object> message = new HashMap<>();
message.put("type", "text");
Map<String, Object> properties = new HashMap<>();
properties.put("message", message);
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
request.mapping(mapping); 

Mapping source provided as a Map which gets automatically converted to JSON format

XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
    builder.startObject("properties");
    {
        builder.startObject("message");
        {
            builder.field("type", "text");
        }
        builder.endObject();
    }
    builder.endObject();
}
builder.endObject();
request.mapping(builder); 

Mapping source provided as an XContentBuilder object, the Elasticsearch built-in helpers to generate JSON content

Index aliases

Aliases can be set at index creation time

request.alias(new Alias("twitter_alias").filter(QueryBuilders.termQuery("user", "kimchy")));  

The alias to define

Providing the whole source

The whole source including all of its sections (mappings, settings and aliases) can also be provided:

request.source("{\n" +
        "    \"settings\" : {\n" +
        "        \"number_of_shards\" : 1,\n" +
        "        \"number_of_replicas\" : 0\n" +
        "    },\n" +
        "    \"mappings\" : {\n" +
        "        \"properties\" : {\n" +
        "            \"message\" : { \"type\" : \"text\" }\n" +
        "        }\n" +
        "    },\n" +
        "    \"aliases\" : {\n" +
        "        \"twitter_alias\" : {}\n" +
        "    }\n" +
        "}", XContentType.JSON); 

The source provided as a JSON string. It can also be provided as a Map or an XContentBuilder.

Optional arguments

The following arguments can optionally be provided:

request.setTimeout(TimeValue.timeValueMinutes(2)); 

Timeout to wait for the all the nodes to acknowledge the index creation as a TimeValue

request.setMasterTimeout(TimeValue.timeValueMinutes(1)); 

Timeout to connect to the master node as a TimeValue

request.waitForActiveShards(ActiveShardCount.from(2)); 
request.waitForActiveShards(ActiveShardCount.DEFAULT); 

The number of active shard copies to wait for before the create index API returns a response, as an int

The number of active shard copies to wait for before the create index API returns a response, as an ActiveShardCount

Synchronous Execution

When executing a CreateIndexRequest in the following manner, the client waits for the CreateIndexResponse to be returned before continuing with code execution:

CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);

Synchronous calls may throw an IOException in case of either failing to parse the REST response in the high-level REST client, the request times out or similar cases where there is no response coming back from the server.

In cases where the server returns a 4xx or 5xx error code, the high-level client tries to parse the response body error details instead and then throws a generic ElasticsearchException and adds the original ResponseException as a suppressed exception to it.

Asynchronous Execution

Executing a CreateIndexRequest can also be done in an asynchronous fashion so that the client can return directly. Users need to specify how the response or potential failures will be handled by passing the request and a listener to the asynchronous create-index method:

client.indices().createAsync(request, RequestOptions.DEFAULT, listener); 

The CreateIndexRequest to execute and the ActionListener to use when the execution completes

The asynchronous method does not block and returns immediately. Once it is completed the ActionListener is called back using the onResponse method if the execution successfully completed or using the onFailure method if it failed. Failure scenarios and expected exceptions are the same as in the synchronous execution case.

A typical listener for create-index looks like:

ActionListener<CreateIndexResponse> listener =
        new ActionListener<CreateIndexResponse>() {

    @Override
    public void onResponse(CreateIndexResponse createIndexResponse) {
        
    }

    @Override
    public void onFailure(Exception e) {
        
    }
};

Called when the execution is successfully completed.

Called when the whole CreateIndexRequest fails.

Create Index Response

The returned CreateIndexResponse allows to retrieve information about the executed operation as follows:

boolean acknowledged = createIndexResponse.isAcknowledged(); 
boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged(); 

Indicates whether all of the nodes have acknowledged the request

Indicates whether the requisite number of shard copies were started for each shard in the index before timing out