开发环境:java8 springboot
pom文件导入依赖
<!--ES所需依赖-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.3.2</version>
</dependency>
连接es返回数据的核心代码:
/**
* 获取ES数据
* @param modules 索引
* @param urlArg url中的部分参数
* @param jsonString 请求体
*/
private String getEsData(String modules,String urlArg,String jsonString) {
RestClient restClient = RestClient.builder(
new HttpHost("192.168.1.1", 9200, "http")).build();
Map<String, String> params = Collections.emptyMap();
HttpEntity entity = new NStringEntity(jsonString, ContentType.APPLICATION_JSON);
String url = "/" + modules + "/" + urlArg;
Response response = null;
try {
response = restClient.performRequest("GET", url,params,entity);
} catch (IOException e) {
log.info("[es] GET请求异常");
e.printStackTrace();
}
String responseBody = "";
try {
assert response != null;
responseBody = EntityUtils.toString(response.getEntity());
log.info("[es]:成功获取搜索数据");
} catch (IOException e) {
e.printStackTrace();
log.info("[es]:获取responseBody异常");
}
try {
restClient.close();
} catch (IOException e) {
e.printStackTrace();
log.info("[es]:restClient关闭异常");
}
return responseBody;
}
获取responseBody之后可用jsonNode等方法对数据进行解析