elasticsearch进行指定字段去重计数,和去重查询(java api)
es7.16.3版本指定字段去重计数RestHighLevelClient client = RestHighLevelClientPoolUtil.getClient();SearchRequest request = new SearchRequest(WebServerDocumentSettings.index);// 构建查询器SearchSourceBuilder builder =
·
es7.16.3版本
指定字段去重计数
RestHighLevelClient client = RestHighLevelClientPoolUtil.getClient();
SearchRequest request = new SearchRequest(WebServerDocumentSettings.index);
// 构建查询器
SearchSourceBuilder builder = new SearchSourceBuilder();
// 指定字段进行折叠,这个字段相同的多条数据只显示其中一条
CollapseBuilder collapseBuilder = new CollapseBuilder("需要去重的字段名");
CardinalityAggregationBuilder agg = AggregationBuilders.cardinality("计数自定义名字").field("指定需要计数的字段");
// 复合查询器
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.matchQuery("field","value");
// 组装查询条件
builder.collapse(collapseBuilder);
builder.sort(WebServerDocumentSettings.Mappings.createTime, SortOrder.DESC);
builder.query(boolQuery);
builder.aggregation(agg);
builder.from(1);
builder.size(10);
// 获取计数信息
ParsedCardinality fileCount = response.getAggregations().get("计数自定义名字");
long total = NumberUtil.parseLong(fileCount.getValueAsString());
for (SearchHit hit : response.getHits().getHits()) {
Map<String, Object> source = hit.getSourceAsMap();
// 转换成实体对象
}
// 关闭client
获取指定索引总数
/**
* 获得索引总数
*
* @param index 索引name
*/
@NotNull
private Long getFieldCounts(String index) throws IOException {
RestHighLevelClient client = RestHighLevelClientPoolUtil.getClient();
CountRequest countRequest = new CountRequest();
countRequest.indices(index);
CountResponse response = client.count(countRequest, RequestOptions.DEFAULT);
RestHighLevelClientPoolUtil.returnClient(client);
return response.getCount();
}
更多推荐
已为社区贡献13条内容
所有评论(0)