// 解析查询 json 格式字符串
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
CloseableHttpClient client = null;
JSONObject searchResult = null;
try {
client = HttpClients.createDefault();
HttpPost post = new HttpPost();
post.setURI(URI.create("http://" + ip + ":" + port + "/" + indexName + "/_search?pretty=true"));
post.setEntity(new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON));
HttpResponse resp = client.execute(post);
String result = IOUtils.toString(resp.getEntity().getContent(), "utf-8");
// 格式化输出 json 格式字符串
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readValue(result, Object.class)));
// 解析 json 格式字符串
JSONObject resultJsonObject = JSONObject.fromObject(JSON.parseObject(result));
if (resultJsonObject.containsKey("error")) {
} else {
searchResult = resultJsonObject.getJSONObject("hits");
}
} catch (Exception exception) {
log.error("Get result failed.", exception);
} finally {
try {
if (client != null) {
client.close();
}
} catch (IOException exception) {
log.error("Close client failed.", exception);
}
}
RESTful 获取 ES Response
最新推荐文章于 2025-05-24 01:32:25 发布