0

我想将 JSON 字符串加载到 Elasticsearch 7.3 版。

以下是我为此使用的代码。

    private RestHighLevelClient restHighLevelClient;
    String jsonString="//here the complete JSON string";
    JSONObject jsonObject = new JSONObject(cojsonStringntent1.toString());
    HashMap<String, Object> hashMap = new Gson().fromJson(jsonObject.toString(), HashMap.class);

    IndexRequest indexRequest = new IndexRequest("index", "type").source(hashMap);
    restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

异常:线程“main”中的异常 java.lang.NullPointerException 在行restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

如果我通过 POSTMEN 发布相同的 jsonString,那么它将完美地加载到 ELASTICSEARCH。

4

2 回答 2

1

根据您的示例代码,您的 restHighLevelClient 根本没有被初始化。请在下面找到如何解决此问题的代码片段:

    @Bean
public RestHighLevelClient elasticRestClient () {
    String[] httpHosts = httpHostsProperty.split(";");
    HttpHost[] httpHostsAsArray = new HttpHost[httpHosts.length];
    int index = 0;

    for (String httpHostAsString : httpHosts) {
        HttpHost httpHost = new HttpHost(httpHostAsString.split(":")[0], new Integer(httpHostAsString.split(":")[1]), "http");
        httpHostsAsArray[index++] = httpHost;
    }

    RestClientBuilder restClientBuilder = RestClient.builder(httpHostsAsArray)
            .setRequestConfigCallback(builder -> builder
                    .setConnectTimeout(connectTimeOutInMs)
                    .setSocketTimeout(socketTimeOutInMs)
            );

    return new RestHighLevelClient(restClientBuilder);
}

并且您的 impl 类使用自动装配的 RestHighLevelClient bean:

    @Autowired
private RestHighLevelClient restClient;
于 2020-05-27T06:52:25.890 回答
1

如果你没有使用 spring(因为它没有提到),你可以使用下面的简单代码来创建一个resthighlevelclient.

在下面的代码中,我正在从配置文件中读取 elasticsearch 配置,随意将其更改为您读取属性或配置的方式,或者如果您只是想快速测试它,硬编码主机和端口的值

RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost(configuration.getElasticsearchConfig().getHost(),
                        configuration.getElasticsearchConfig().getPort(),
                        "http")));
于 2020-05-27T10:21:09.730 回答