anthony hdhdh :
My mapping is too long and to optimize my code i would like to put the json format of the mapping in a json file and load it with elasticsearch java api. But i didn't find a way to do that. I want to use this mapping just for one index not for all.
Opster Elasticsearch Ninja :
Hint is already given by @Val, But as I use it my code and had code for this handy, so thought of posting it here :
Utility code to read JSON mapping from a file in a String format:
/**
* Get String from file Which contains Index mapping in JSON format.
*
* @param fileName file which needs to be read into JSON.
* @return
*/
public String getStringFromFile(String fileName) throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
InputStream in = classLoader.getResourceAsStream(fileName);
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());
}
Using above code, you can easily create an index, using the CreateIndexRequest
API of java high-level elasticsearch rest client:
void createIndex(RestHighLevelClient client) throws IOException, URISyntaxException {
if (!isIndexExist(client, indexName)) {
String indexString = getStringFromFile("your file name");
CreateIndexRequest request = new CreateIndexRequest(indexName);
request.source(indexString, XContentType.JSON);
client.indices().create(request, RequestOptions.DEFAULT);
}
}
Let me know if you face any issue and have doubt in any loc.