[英]is there a way to load a json file containing the mapping of an index with the elasticsearch java api?
我的映射太长,为了优化我的代码,我想将映射的 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);
}
}
如果您遇到任何问题并且对任何地方有疑问,请告诉我。
迟到的帖子。
这可以使用apache commons-io
在一行中实现。
添加依赖项:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
然后在代码中简单地做:
String jsonFileinString = FileUtils.readFileToString(new File("Your File"), "UTF-8")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.