美文网首页
[ElasticSearch] Aggregation :Met

[ElasticSearch] Aggregation :Met

作者: PowerMe | 来源:发表于2018-01-29 19:50 被阅读25次

    SQL场景:Metrics查询

    SELECT avg(privce)  FROM table where price >= 10000 and price <= 35000 GROUP BY color
    

    查询在一定价格区间的,按颜色分组的平均值
    Aggregation API:
    在API实现上是先做过滤再聚合,分桶后加入Metrics聚合:

    GET /cars/transactions/_search
    {
        "size" : 0,
        "query": {
            "range" : {
                "price" : {
                    "gte" : 10000,
                    "lt" :  35000
                }
            }
        },
        "aggs" : { 
            "popular_colors" : { 
                "terms" : { 
                  "field" : "color"
                },
                "aggs": {
                  "price_avg": {
                    "avg": {
                      "field": "price"
                    }
                  }
                }
            }
        }
    }
    

    结果:


    image.png

    java API:

    def aggTest3(): Unit = {
        import scala.collection.JavaConverters._
        val rangeQuery = QueryBuilders.rangeQuery("price").gte(10000).lt(35000)
        val agg = AggregationBuilders
          .terms("color")
          .field("color")
          .order(Terms.Order.count(false))
        val avg = AggregationBuilders
        .avg("price")// also sum / max
        .field("price")
        agg.subAggregation(avg)
        val searchRes = queryBuilder
          .setQuery(rangeQuery)
          .addAggregation(agg)
          .execute()
          .actionGet()
        searchRes.getAggregations.get("color").asInstanceOf[Terms].getBuckets.asScala.foreach{ bucket =>
          println(s"key: ${bucket.getKeyAsString}, value ${bucket.getDocCount}")
          bucket.getAggregations.getAsMap.asScala.foreach{ agg =>
            println(s"key: ${agg._1}, value ${agg._2.asInstanceOf[InternalAvg].getValue}")
          }
          println(s"----------------------------------------")
        }
      }
    

    结果:


    image.png

    相关文章

      网友评论

          本文标题:[ElasticSearch] Aggregation :Met

          本文链接:https://www.haomeiwen.com/subject/onsfzxtx.html