当前位置: 首页 > news >正文

es高级查询——多字段聚合

目录

1、需求 

2、es查询

3、java实现


1、需求 

查询需求类似下面sql:

select apiId,bmdm,avg(dyhs)  as avg_dyhs,count(cwm='0') as sbcs from tj_sjb

group by apiId,bmdm

2、es查询

POST /xx_doc/_search

{

    "query": {

        "bool": {

            "must": [],

            "must_not": [],

            "should": []

        }

    },

    "from": 1,

    "size": 0,

    "sort": [],

    "aggs": {

        "pre": {

            "terms": {

                "script": "doc['apiId'].value +'_'+ doc['bmdm'].value",

                "size": 1

            },

            "aggs": {

                "avg_dyhs": {

                    "avg": {

                        "field": "dyhs"

                    }

                },

                "count_sbcs": {

                    "filter": {

                        "term": {

                            "type": "0"

                        }

                    },

                    "aggs": {

                        "sbcs": {

                            "value_count": {

                                "field": "cwm"

                            }

                        }

                    }

                }

            }

        }

    },

    "track_total_hits": true

}

结果


{"took": 240,"timed_out": false,"_shards": {"total": 4,"successful": 4,"skipped": 0,"failed": 0},"hits": {"total": {"value": 133771,"relation": "eq"},"max_score": null,"hits": []},"aggregations": {"pre": {"meta": {},"doc_count_error_upper_bound": 5,"sum_other_doc_count": 93042,"buckets": [{"key": "02024080716254956700000101416459_BM800002232","doc_count": 40729,"count_sbcs": {"meta": {},"doc_count": 0,"sbcs": {"value": 0}},"avg_dyhs": {"value": 8530.576542512707}}]}}
}

3、java实现

private void esTj(Long startHourTime, Long endHourTime, String formatedTime) {Script script = new Script("doc['apiId'].value +'_'+ doc['bmdm'].value+'_'+ " +"doc['yyId'].value+'_'+ doc['apiYyId'].value");// es查询List<WdDytj> wdDytjList = new ArrayList<>(Constants.DEFAULT_SIZE);SearchRequest searchRequest = new SearchRequest(EsConstant.XX_DOC);AggregationBuilder termsBuilder = AggregationBuilders.terms("by_group").script(script).size(10000);AvgAggregationBuilder avgAggBuilder = AggregationBuilders.avg("avg_dyhs").field("dyhs");AggregationBuilder counSbcsAggBuilder = AggregationBuilders.filters("count_sbcs",new FiltersAggregator.KeyedFilter("sbcs",QueryBuilders.boolQuery().mustNot(QueryBuilders.termsQuery("cwm", "0"))));termsBuilder.subAggregation(avgAggBuilder).subAggregation(counSbcsAggBuilder);SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();searchSourceBuilder.aggregation(termsBuilder);BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("dysj").gte(startHourTime).lt(endHourTime);boolQuery.must(rangeQueryBuilder);searchSourceBuilder.query(boolQuery).size(0);searchRequest.source(searchSourceBuilder);// 执行es中的查询方法SearchResponse response = null;try {// 获取es中查询数据response = EsDynamicSource.getCurClient().search(searchRequest, RequestOptions.DEFAULT);// 取出es中的数据并且进行判断if (response != null) {Terms agg = response.getAggregations().get("by_group");if (agg != null) {for (Terms.Bucket bucket : agg.getBuckets()) {WdDytj wdDytj = new WdDytj();ParsedAvg avgDyhs = (ParsedAvg) bucket.getAggregations().asMap().get("avg_dyhs");ParsedFilters countSbcs = (ParsedFilters) bucket.getAggregations().asMap().get("count_sbcs");wdDytj.setDycs(bucket.getDocCount());wdDytj.setDyhs(avgDyhs.getValue());wdDytj.setSbcs(countSbcs.getBucketByKey("sbcs").getDocCount());wdDytj.setSjbs(formatedTime);String key = bucket.getKeyAsString();//apiId_bmdm_yyId_apiYyIdString[] keys = key.split("_");String now = String.valueOf(System.currentTimeMillis());wdDytj.setApiId(keys[0]);wdDytj.setApiYyId(keys[3]);wdDytj.setBmdm(keys[1]);wdDytj.setYyId(keys[2]);}}}} catch (Exception e) {}
}

http://www.mrgr.cn/news/34073.html

相关文章:

  • 批量将当前目录里的所有pdf 转化为png 格式
  • odoo17 owl 前端 顶部导航栏右侧添加自定义按钮
  • Qt_day10_程序打包(完结)
  • MySQL中字段类型和Java对象中的数据类型对应关系
  • [2024最新] java八股文实用版(附带原理)---java集合篇
  • GitLab 降级安装出现 500 错误,如何解决?
  • 75、Python之函数式编程:生成器的核心方法及更多使用场景
  • 文科生学pytorch——一些概念的解释
  • layui upload.render 设置文件名
  • 基于Python+SQLServer实现(界面)书店销售管理管理子系统
  • 关于在vue2中给el-input框的placeholder加样式
  • CPLD 工程师面试题
  • AI美女占领小红书,卷翻真人女网红
  • HTML5简介的水果蔬菜在线商城网站源码系列模板3
  • Oracle数据库高级技术解析与实战案例
  • 【AIGC】ChatGPT提示词助力高效文献处理、公文撰写、会议纪要与视频总结
  • 详解运行时安全检测神器:Falco
  • [leetcode]70_单词搜索
  • 如何将py文件打包成exe文件?---pyinstaller使用方法
  • Java面试篇基础部分- 锁详解
  • 【C++掌中宝】玩转C++标准输入输出(简洁明了)
  • JVM面试问题集
  • 【aider】aider使用ollama本地模型
  • cmake--add_compile_options
  • MQ(消息队列)重启后消息是否会丢失
  • AI大模型优化指南:RAG、提示工程与微调的应用场景解析