The easiest way to create(as its nested) is to put this mapping in JSON format
in the file and then read it in string format(provided utility methods) and creates the mapping as shown below:
Other ways are mentioned in this official doc.
Create a file named nested.mapping
and I will use the nested
as an index name.
Use following utility method to read the file and return it in string
format
public String getStringFromFile(String fileName) throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
InputStream in = classLoader.getResourceAsStream(fileName); --> file name
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(StandardCharsets.UTF_8.name());
}
Resthighlevelclient code to create an index using above utility method
if (!isIndexExist(client, indexName)) {
JsonUtil jsonUtil = new JsonUtil();
String indexString = jsonUtil.getStringFromFile(indexName + ".mapping");
CreateIndexRequest request = new CreateIndexRequest(indexName);
request.source(indexString, XContentType.JSON);
client.indices().create(request, RequestOptions.DEFAULT);
}
Please see my java debugger screen-shot, which read this file properly in JSON
format.

Finally, Elastic mapping API result, which shows index created successfully.
{
"nested": {
"aliases": {
},
"mappings": {
"properties": {
"events": {
"type": "nested",
"properties": {
"ecommerceData": {
"type": "nested",
"properties": {
"comments": {
"type": "nested",
"properties": {
"recommendationType": {
"type": "keyword"
}
}
}
}
}
}
}
}
}
}