Create Index API

edit

Create Index Request

edit

A CreateIndexRequest requires an index argument:

CreateIndexRequest request = new CreateIndexRequest("twitter"); 

The index to create

Index settings

edit

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

edit

An index may be created with mappings for its document types

request.mapping("_doc", 
        "{\n" +
        "  \"_doc\": {\n" +
        "    \"properties\": {\n" +
        "      \"message\": {\n" +
        "        \"type\": \"text\"\n" +
        "      }\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> jsonMap = new HashMap<>();
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);
jsonMap.put("_doc", mapping);
request.mapping("_doc", jsonMap); 

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

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

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

request.mapping("_doc", "message", "type=text"); 

Mapping source provided as Object key-pairs, which gets converted to JSON format

Index aliases

edit

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

edit

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" +
        "        \"_doc\" : {\n" +
        "            \"properties\" : {\n" +
        "                \"message\" : { \"type\" : \"text\" }\n" +
        "            }\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

edit

The following arguments can optionally be provided:

request.timeout(TimeValue.timeValueMinutes(2)); 
request.timeout("2m"); 

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

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

request.masterNodeTimeout(TimeValue.timeValueMinutes(1)); 
request.masterNodeTimeout("1m"); 

Timeout to connect to the master node as a TimeValue

Timeout to connect to the master node as a String

request.waitForActiveShards(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

edit

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

edit

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

edit

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