我的映射太长,为了优化我的代码,我想将映射的 json 格式放入 json 文件中,并使用 elasticsearch java api 加载它。但我没有找到办法做到这一点。我只想将此映射用于一个索引,而不是所有索引。
最佳答案
@Val 已经给出了提示,但是当我使用它时,我的代码并且有方便的代码,所以考虑将其发布在这里:
从字符串格式的文件中读取 JSON 映射的实用程序代码:
/**
* 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());
}
使用上面的代码,您可以使用java高级elasticsearch Rest客户端的CreateIndexRequest
API轻松创建索引:
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);
}
}
如果您遇到任何问题并对任何地点有疑问,请告诉我。
关于java - 有没有办法使用elasticsearch java api加载包含索引映射的json文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57767151/