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();
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐