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

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_apiYyId
                    String[] 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.kler.cn/a/322291.html

相关文章:

  • kvm-dmesg:从宿主机窥探虚拟机内核dmesg日志
  • Docker入门之Windows安装Docker初体验
  • qt之QFTP对文件夹(含嵌套文件夹和文件)、文件删除下载功能
  • 【多状态dp】买卖股票的最佳时机III
  • R语言 | 宽数据变成一列,保留对应的行名和列名
  • 14. 乘法口诀挑战赛
  • Spring在不同类型之间也能相互拷贝?
  • 【java17】java17新特性之Stream.toList()
  • 3271.哈希分割子串
  • 前端使用vue点击上传文件,传送给后端,后端进行文件接收
  • 区块链—共享块存储安全可信任可追踪分布式数据库系统技术
  • LTE SSS产生过程中z序列的介绍和MATLAB以及C语言实现
  • 7个不为人知的实用软件推荐
  • 关于VSCode里需要用的一些插件总结
  • 19 基于51单片机的倒计时音乐播放系统设计
  • USB 3.1 标准 A 型到 USB 3.1 标准 A 型或 B 型的电缆组件
  • Spring MVC 基础 : 文件、cookies的接收 ,REST响应
  • python命令行怎么换行
  • Python批量处理客户明细表格数据,挖掘更大价值
  • 电脑退域或切换系统账号后系统黑屏
  • C#基于SkiaSharp实现印章管理(8)
  • 这五本大模型书籍,让你从大模型零基础到精通,非常详细收藏我这一篇就够了
  • 【PyTorch】环境配置
  • MySQL 数据转换技巧:列转行与行转列
  • Redis支持数据类型,它们各自的应用场景是
  • 基于以太坊+IPFS的数据交易平台进行效率评估