You can use the implementation from the ElasticsearchRestTemplate itself.
Using Elasticsearch 6.x:
This is how you create the index with settings:
@Override
public boolean createIndex(String indexName, Object settings) {
CreateIndexRequest request = new CreateIndexRequest(indexName);
if (settings instanceof String) {
request.settings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE);
} else if (settings instanceof Map) {
request.settings((Map) settings);
} else if (settings instanceof XContentBuilder) {
request.settings((XContentBuilder) settings);
}
try {
return client.indices().create(request, RequestOptions.DEFAULT).isAcknowledged();
} catch (IOException e) {
throw new ElasticsearchException("Error for creating index: " + request.toString(), e);
}
}
This is how you update the mappings for the index:
@Override
public boolean putMapping(String indexName, String type, Object mapping) {
Assert.notNull(indexName, "No index defined for putMapping()");
Assert.notNull(type, "No type defined for putMapping()");
PutMappingRequest request = new PutMappingRequest(indexName).type(type);
if (mapping instanceof String) {
request.source(String.valueOf(mapping), XContentType.JSON);
} else if (mapping instanceof Map) {
request.source((Map) mapping);
} else if (mapping instanceof XContentBuilder) {
request.source((XContentBuilder) mapping);
}
try {
return client.indices().putMapping(request, RequestOptions.DEFAULT).isAcknowledged();
} catch (IOException e) {
throw new ElasticsearchException("Failed to put mapping for " + indexName, e);
}
}
Using Elasticsearch 7.x:
- You need to create a variable
IndexCoordinates.of("indexName")
- Get the IndexOperations from the ElasticSearchTemplate for that index
- Create your index via the indexOperations variable like this:
IndexOperations indexOperations = elasticsearchTemplate.indexOps(indexCoordinates);
String indexSettings = "" //Pass json string here
String mappingJson = "" //Pass json string here
Document mapping = Document.parse(mappingJson);
Map<String, Object> settings = JacksonUtil.fromString(indexSettings, new TypeReference<>() {});
indexOperations.create(settings, mapping);
indexOperations.refresh(); //(Optional) refreshes the doc count
It really depends on which spring-data-elasticsearch you are using. Feel free to checkout the documentation as well:
https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#new-features
Hope this helps with your elasticsearch journey! Feel free to ask more questions regarding the java implementation :)