elasticsearch,mapping,Java,elasticsearch,Mapping" /> elasticsearch,mapping,Java,elasticsearch,Mapping" />

有没有办法加载一个json文件,其中包含使用elasticsearch java api的索引映射?

有没有办法加载一个json文件,其中包含使用elasticsearch java api的索引映射?,java,elasticsearch,mapping,Java,elasticsearch,Mapping,我的映射太长,为了优化代码,我想将映射的json格式放在json文件中,并用ElasticSearchJavaAPI加载它。但是我没有找到一个办法。我只想将此映射用于一个索引,而不是所有索引。提示已经由@Val给出,但当我使用它时,我的代码和代码都很方便,所以考虑将其发布在这里: 从字符串格式的文件读取JSON映射的实用程序代码: /** * Get String from file Which contains Index mapping in JSON format. * * @par

我的映射太长,为了优化代码,我想将映射的json格式放在json文件中,并用ElasticSearchJavaAPI加载它。但是我没有找到一个办法。我只想将此映射用于一个索引,而不是所有索引。

提示已经由@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);
            }
    }
如果您面临任何问题并且对loc有任何疑问,请告诉我。

后期发布

这可以通过使用apache commons io在一行中实现

添加依赖项:

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.7</version>
        </dependency>

它必须是elasticsearch java api,还是使用curl调用的elasticsearch REST api也是一个解决方案?使用java api,您可以使用java IO/NIO轻松读取文件内容,然后发送该内容。感谢您的回复,我找到了一个使用@Val solution的解决方案。我读取了我的文件,并将内容存储在一个字符串变量中,然后将该变量传递给映射请求。您可能应该添加一个答案并显示您所做的操作,因为其他人可能会觉得这很有帮助;-)@Val,我在我的项目中大量使用了它,并提供了包含代码的答案:-)
String jsonFileinString = FileUtils.readFileToString(new File("Your File"), "UTF-8")