美文网首页
[ElasticSearch] Aggregation :带过滤

[ElasticSearch] Aggregation :带过滤

作者: PowerMe | 来源:发表于2018-01-24 08:39 被阅读78次

    SQL场景:带过滤条件的聚合查询

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

    查询在一定价格区间内的销售车辆颜色分布

    Aggregation API:
    在API实现上是先做过滤再聚合

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

    java API:

    def aggTest2(): Unit = {
        import scala.collection.JavaConverters._
       // 构造RangeQuery
        val rangeQuery = QueryBuilders.rangeQuery("price").gte(10000).lt(35000)
    
      // 构造Aggregation
        val agg = AggregationBuilders
          .terms("color")
          .field("color")
          .order(Terms.Order.count(false))
    
      // 组合&执行查询
        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}")
        }
      }
    

    相关文章

      网友评论

          本文标题:[ElasticSearch] Aggregation :带过滤

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