场景
springboot 在整合elasticsearch 通常会受到elasticsearch 版本的影响,
1.一套代码可能要兼容多个elasticsearch 的情况
2.低版本的无法调用高版本一些方法(例如:delete_by_query)
实现逻辑
用高版本的去做参数封装,用restTemplate 去发送请求(草台战法)
实现代码
依赖
java
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.14</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>5.6.14</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.2.4</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</exclusion>
</exclusions>
</dependency>
示例代码
我们以_delete_by_query 为例
java
@Autowired
private RestTemplate restTemplate;
private ResponseEntity<JSONObject> deleteByQuery2() {
//构建查询体
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//构建查询条件
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("create_time");
rangeQueryBuilder.lt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
rangeQueryBuilder.gte(LocalDateTime.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
searchSourceBuilder.postFilter(rangeQueryBuilder);
//打印请求体
log.debug("请求体:{}", searchSourceBuilder);
//发送请求
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity httpEntity = new HttpEntity(searchSourceBuilder.toString(), httpHeaders);
ResponseEntity<JSONObject> resp = restTemplate.postForEntity("http://127.0.0.1:9200/order_index/_delete_by_query", httpEntity, JSONObject.class);
if (resp.getStatusCode().equals(HttpStatus.OK)) {
JSONObject body = resp.getBody();
log.debug(body.toString(SerializerFeature.DisableCircularReferenceDetect));
}
return resp;
}
参考这个逻辑去处理部分问题(用自带的请求(searchrequest),部分功能受到版本限制)