elasticsearch对聚合后的结果进行范围筛选

导读:本篇文章讲解 elasticsearch对聚合后的结果进行范围筛选,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

书接上文,
上一篇文章写了elasticsearch对聚合后的结果排序

这一篇写对聚合后的范围筛选。

一般的我们可以在query或filter里使用range进行范围筛选查询,但是我们在聚合里怎么对聚合后的结果筛选出符合范围的聚合结果呢?

dsl语句如下:

  "aggregations": {
    "statistics_assets": {
      "terms": {
        "field": "one_account.one_account_no",
        "size": 10
      },
      "aggregations": {
        "assets": {
          "sum": {
            "field": "assets.merge"
          }
        },
        "assets_sum_range": {
          "bucket_selector": {
            "buckets_path": {
              "key": "assets"
            },
            "script": {
              "source": "0<=params.key&&params.key<=100000",
              "lang": "painless"
            }
          }
        }
      }
    }
  }

assets_sum_range中使用bucket_selector对sum聚合后的”assets.merge”结果进行筛选,筛选的条件范围是0<=聚合结<=100000

Java代码:

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("statistics_assets")
                   .field("one_account.one_account_no")
                   .size(10);       
AggregationBuilder assetsAggregation = AggregationBuilders.sum("assets").field("assets.merge");
termsAggregationBuilder.subAggregation(assetsAggregation);

 //对聚合后的总资产进行范围选择
   Map<String, String> bucketsPathsMap = new HashMap<>();
   bucketsPathsMap.put("key", "assets");
   Script script = new Script( "0<=params.key&&params.key<=100000" );
   BucketSelectorPipelineAggregationBuilder bs = PipelineAggregatorBuilders.bucketSelector("assets_sum_range", bucketsPathsMap, script);
   termsAggregationBuilder.subAggregation(bs);

searchSourceBuilder.aggregation(termsAggregationBuilder);

最后输出的结果便是0-100000范围的聚合结果:

  "aggregations" : {
    "statistics_assets" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 4,
      "buckets" : [
        {
          "key" : "110600000973",
          "doc_count" : 2,
          "assets" : {
            "value" : 0.0
          }
        },
        {
          "key" : "105100015207",
          "doc_count" : 1,
          "assets" : {
            "value" : 9.999
          }
        }
      ]
    }
  }

参考文章:
elasticsearch – how to make bucket filter in java api

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/80340.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!