Elasticsearch 聚合(aggregation)查询返回所有
- Elasticsearch教程(一),全程直播(小白级别)
- Elasticsearch教程(二),IK分词器安装
- Elasticsearch教程(三),IK分词器安装 (极速版)
- Elasticsearch安装(四), elasticsearch head 插件安装和使用。
- Elasticsearch教程(五) elasticsearch Mapping的创建
- Elasticsearch教程(六) elasticsearch Client创建
- Elasticsearch教程(七) elasticsearch Insert 插入数据(Java)
- Elasticsearch教程(八) elasticsearch delete 删除数据(Java)
- Elasticsearch教程(九) elasticsearch 查询数据 | 分页查询
- Elasticsearch权威指南-中文.pdf
Elasticsearch 做查询的时候,很多情况下,有一些查询满足不了我们的要求,这个时候,我们用Elasticsearch
的聚合(aggregation
)函数,下面讲讲aggregation
的使用姿势。
Elasticsearch 做聚合查询的时候。
{
"from": 0,
"size": 10,
"aggregations": {
"types": {
"terms": {
"field": "types"
}
}
}
}
AggregationBuilder<?> aggregation = AggregationBuilders.terms("types").field("types");
SearchRequestBuilder srb = client.prepareSearch(BaseMapping.index);
srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
SearchResponse response = srb.execute().actionGet();
Aggregations agg = response.getAggregations();
Terms types = agg.get("types");
这样都可以获取到聚合数据。按照字段 types
进行聚合查询。这个时候返回是10
条聚合数据。但是我想返回所有的呢?
我看了源码,个人觉得比较坑。
/**
* Sets the size - indicating how many term buckets should be returned (defaults to 10)
*/
public TermsBuilder size(int size) {
bucketCountThresholds.setRequiredSize(size);
return this;
}
这里说了,在后面加size
可以指定返回条数,默认是10
条。但是没说明,我要全部的数据的size(0)
的问题。
后来查询资料,没找到相关资料,问其他同学,得到结果,size(-1)
or size(0)
试试,结果我觉得-1
的正确几率大点,结果报错,从错误来看,说size
必须大于或者等于0
,试试0
,结果返回全部,也就是Global
。得到如下写法。
{
"from": 0,
"size": 10,
"aggregations": {
"types": {
"terms": {
"field": "types",
"size": 0
}
}
}
}
Java API
//设置一个叫 types 聚合,聚合字段是types(这里可以多个),然后 size = 0 标示全局
AggregationBuilder<?> aggregation = AggregationBuilders.terms("types").field("types").size(0);
SearchRequestBuilder srb = client.prepareSearch(BaseMapping.index);
srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
SearchResponse response = srb.execute().actionGet();
Aggregations agg = response.getAggregations();
//取到聚合数据
Terms types = agg.get("types");
哦了!
版权所属:SO JSON在线解析
原文地址:https://www.sojson.com/blog/150.html
转载时必须以链接形式注明原始出处及本声明。
如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。