我想将一个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中。
如果你没有使用spring(因为它没有提到(,你可以使用下面的简单代码创建一个resthighlevelclient
。
在下面的代码中,我正在从配置文件中读取 elasticsearch 配置,请随意将其更改为您读取属性或配置的方式,或者如果您只是想快速测试它对主机和端口的值进行硬编码
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
RestClient.builder(new HttpHost(configuration.getElasticsearchConfig().getHost(),
configuration.getElasticsearchConfig().getPort(),
"http")));
根据你的示例代码,你的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;