工作需要,专门花了一下午研究了Elasticsearch里面的nested。最好的材料还是官网上面的,
所以直接将里面涉及到nested的文章找来看了看,顺便把它们翻译了,贴出来和大家分享。同时综合考虑了一下,把英语大体的
英文原文也一起贴出来了。希望这样能够适应不同读者的口味。
2.
备注:nested在5篇文章内特意没有翻译。毕竟在你不能在编程的时候将nested写成“嵌套”。其他一些比如,object,
document的翻译,个人是不喜欢翻译成中文的。不过文章中大多数地方还是将他们分别翻译成对象和文本。
在ES里面所有的聚合实例都由AggregationBuilders类提供静态方法构造,我们先看下常用有哪些方法使用:
Java代码
- (1)统计某个字段的数量
- ValueCountBuilder vcb= AggregationBuilders.count("count_uid").field("uid");
- (2)去重统计某个字段的数量(有少量误差)
- CardinalityBuilder cb= AggregationBuilders.cardinality("distinct_count_uid").field("uid");
- (3)聚合过滤
- FilterAggregationBuilder fab= AggregationBuilders.filter("uid_filter").filter(QueryBuilders.queryStringQuery("uid:001"));
- (4)按某个字段分组
- TermsBuilder tb= AggregationBuilders.terms("group_name").field("name");
- (5)求和
- SumBuilder sumBuilder= AggregationBuilders.sum("sum_price").field("price");
- (6)求平均
- AvgBuilder ab= AggregationBuilders.avg("avg_price").field("price");
- (7)求最大值
- MaxBuilder mb= AggregationBuilders.max("max_price").field("price");
- (8)求最小值
- MinBuilder min= AggregationBuilders.min("min_price").field("price");
- (9)按日期间隔分组
- DateHistogramBuilder dhb= AggregationBuilders.dateHistogram("dh").field("date");
- (10)获取聚合里面的结果
- TopHitsBuilder thb= AggregationBuilders.topHits("top_result");
- (11)嵌套的聚合
- NestedBuilder nb= AggregationBuilders.nested("negsted_path").path("quests");
- (12)反转嵌套
- AggregationBuilders.reverseNested("res_negsted").path("kps ");
Java代码
- SearchRequestBuilder search = client.prepareSearch("index").setTypes("type");
- TermsBuilder one= AggregationBuilders.terms("group_name").field("name");
- TermsBuilder two= AggregationBuilders.terms("group_age").field("age");
- one.subAggregation(two)
- search.addAggregation(one);
- Terms terms= search.get().getAggregations().get("group_name");
- for(Terms.Bucket name_buk:terms.getBuckets()){
- //一级分组的内容
- Terms terms_age= name_buk.getAggregations().get("group_age");
- for(Terms.Bucket age_buk:terms_age.getBuckets()){
- //二级分组的内容
- System.out.println(name_buk.getKey()+" "+age_buk.getKey()+" "+age_buk.getDocCount());
- }
- }
Java代码
- - //嵌套查询root节点
- NestedBuilder nestedBuilder= AggregationBuilders.nested("negsted").path("quests");
- //嵌套查询的子查询中分组count
- TermsBuilder tb= AggregationBuilders.terms("group_name").field("quests.name");
- //添加子查询到root节点里面
- nestedBuilder.subAggregation(tb);
- //获取一级嵌套
- Nested ntd= search.get().getAggregations().get("negsted");
- //打印一级嵌套的结果
- System.out.println(ntd.getDocCount());
- //从一级嵌套查询的结果中获取二级嵌套查询结果
- Terms term= ntd.getAggregations().get("group_name");
- //获取嵌套下面的结果
- for(Terms.Bucket tbket:term.getBuckets()){
- System.out.println(tbket.getKey()+" "+tbket.getDocCount());
- }
https://blog.csdn.net/allenalex/article/details/45044425
http://qindongliang.iteye.com/blog/2363929
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html