是什么
es官网推荐的es客户端组件RestHighLevelClient, 其封装了操作es的crud方法,底层原理就是模拟各种es需要的请求,如put,post,delete,get等方式
使用步骤
引入pom依赖
application.yml配置ES
查询
// 构建查询参数
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 指定返回字段
String[] includes = new String[]{"name", "age"};
String[] excludes = new String[]{"sex"};
searchSourceBuilder.fetchSource(includes, excludes);
// 构建条件查询
// and = filter/must; or = should
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
searchSourceBuilder.query(boolQueryBuilder.filter(QueryBuilders.termsQuery("id", ids)));
// 时间范围查询
searchSourceBuilder.query(boolQueryBuilder.filter(QueryBuilders.rangeQuery("created_time").from(queryVO.getCreatedTime())));
searchSourceBuilder.query(boolQueryBuilder.filter(QueryBuilders.rangeQuery("created_time").to(queryVO.getEndTime())));
// 分页
Integer size = queryVO.getSize();
Integer from = (queryVO.getPage()-1)*queryVO.getSize();
if (size + from > 10000) {
throw new RRException("分页参数不合理,暂不处理");
}
searchSourceBuilder.size(size);
searchSourceBuilder.from(from);
searchSourceBuilder.query(boolQueryBuilder);
// 构建请求
SearchRequest searchRequest = new SearchRequest(EsOperateTables.EXCEPTION_HANDLE.getAlias());// ES索引别名
searchRequest.source(searchSourceBuilder);
// 发起请求
SearchResponse searchResponse = new SearchResponse();
try {
searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
log.error(ErrorMsgConstant.ES_QUERY_ERROR, e);
throw new RRException(ErrorMsgConstant.ES_QUERY_ERROR);
}
// 解析SearchResponse
long totalHits = searchResponse.getHits().getTotalHits();
List<Map<String, Object>> mapList = Lists.newArrayListWithCapacity(searchResponse.getHits().getHits().length);
Arrays.stream(searchResponse.getHits().getHits()).forEach(hit -> mapList.add(hit.getSourceAsMap()));
List<ResInfo> resInfos = new ArrayList<>();
if (CollectionUtils.isNotEmpty(mapList)) {
resInfos = JSON.parseArray(JSON.toJSONString(mapList), ResInfo.class);
}