我的映射太长,为了优化我的代码,我想将映射的json格式放在json文件中,并用elasticsearch java api加载它。但是我没有找到一种方法。我只想对一个索引使用此映射,而不是对所有索引使用。
答案 0 :(得分:2)
@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);
}
}
如果您遇到任何问题并且对任何地方有疑问,请告诉我。
答案 1 :(得分:0)
最新帖子。
这可以使用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")