• ES 查询实战


    ES语句和SQL语句对比
    初始化Builder:SearchRequestBuilder sbuilder = client.prepareSearch("player").setTypes("player");
    一、分组查询

    1、根据team分组
    (1)SQL写法
    select team, count(*) as player_count from player group by team;
    (2)ES写法
    TermsBuilder teamAgg= AggregationBuilders.terms("player_count ").field("team");
    sbuilder.addAggregation(teamAgg);
    SearchResponse response = sbuilder.execute().actionGet();
    2、根据team、position分组
    (1)SQL写法
    select team, position, count(*) as pos_count from player group by team, position;
    (2)ES写法
    TermsBuilder teamAgg= AggregationBuilders.terms("player_count ").field("team");
    TermsBuilder posAgg= AggregationBuilders.terms("pos_count").field("position");
    sbuilder.addAggregation(teamAgg.subAggregation(posAgg));
    SearchResponse response = sbuilder.execute().actionGet();
    3、根据team分组,并计算最大年龄
    (1)SQL写法
    select team, max(age) as max_age from player group by team;
    (2)ES写法
    TermsBuilder teamAgg= AggregationBuilders.terms("player_count ").field("team");
    MaxBuilder ageAgg= AggregationBuilders.max("max_age").field("age");
    sbuilder.addAggregation(teamAgg.subAggregation(ageAgg));
    SearchResponse response = sbuilder.execute().actionGet();

    聚合操作主要是调用了SearchRequestBuilder的addAggregation方法,通常是传入一个TermsBuilder,子聚合调用TermsBuilder的subAggregation方法,可以添加的子聚合有TermsBuilder、SumBuilder、AvgBuilder、MaxBuilder、MinBuilder等常见的聚合操作。

    从实现上来讲,SearchRequestBuilder在内部保持了一个私有的 SearchSourceBuilder实例, SearchSourceBuilder内部包含一个List<AbstractAggregationBuilder>,每次调用addAggregation时会调用 SearchSourceBuilder实例,添加一个AggregationBuilder。
    同样的,TermsBuilder也在内部保持了一个List<AbstractAggregationBuilder>,调用addAggregation方法(来自父类addAggregation)时会添加一个AggregationBuilder。

    二、时间查询

    dateHistogram 时间查询,区间上支持了日期的表达式,按月查询

    {
    "aggs":{
        "articles_over_time":{
            "date_histogram":{
                "field":"date",
                "interval":"month"
                }
            }
        }
    }
  • 相关阅读:
    Forethought Future Cup
    2020 CSP-S T3 函数调用(拓扑序+后缀积)
    欧拉图论定理 公式及证明
    2020 CSP-J T3 表达式(栈+二叉树)
    eJOI2018 Problem D Chemical table(二分图+并查集)
    洛谷 P5089 [eJOI2018]元素周期表(二分图+并查集)
    eJOI 2017 Problem A Magic(前缀和+排序)
    洛谷 P6273 [eJOI2017]魔法(前缀和+排序)
    OI常见解题思路技巧大汇总【不定期更新】
    JZOJ 6840. 【2020.11.5提高组模拟】铲雪(线段树)
  • 原文地址:https://www.cnblogs.com/zhuziyu/p/10613664.html
Copyright © 2020-2023  润新知