Elasticsearch根据条件统计结果数量
post ip:port/index/type/_search
{
"from": 0,
"size": 0,
"query": {
"bool": {
"must": [{
"match_phrase": {
"name": {
"query": "aaaa",
"slop": 0,
"boost": 1
}
}
},
{
"range": {
"startTime": {
"from": 1661616000391,
"to": null,
"include_lower": true,
"include_upper": true,
"boost": 1
}
}
}
]
}
},
"_source": {
"includes": [
"COUNT"
],
"excludes": []
},
"aggregations": {
"COUNT(*)": {
"value_count": {
"field": "_index"
}
}
}
}
java代码:
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
AggregationBuilder sumAggregationBuilder = AggregationBuilders.count("count").field("_index");
sourceBuilder.aggregation(sumAggregationBuilder);
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
//查询条件
queryBuilder.must(QueryBuilders.matchPhraseQuery("name.keyword",name));
queryBuilder.must(QueryBuilders.rangeQuery("startTime").gte(startTime));
//设置条件和结果数量
sourceBuilder.query(queryBuilder).from(0).size(0);
//查询索引对象
SearchRequest searchRequest = new SearchRequest(index).types(type).source(sourceBuilder);
//不同版本请求ES的方式不一样
SearchResponse response = client.search(searchRequest).actionGet();
SearchResponse response = client.getClient().search(rq,RequestOptions.DEFAULT);
//返回结果
long total = response.getHits().getTotalHits();