Elasticsearch桶聚合和管道聚合

1. 根据名称统计数量 

GET order/_search
{
  "_source": false,
  "aggs": {
    "aggs_name": {  // 自定义查询结果名称
      "terms": {  // 使用的函数
        "field": "name.keyword"
      }
    }
  }
}

查询结果例子:
"aggregations" : {
  "aggs_name" : {
    "doc_count_error_upper_bound" : 0,
    "sum_other_doc_count" : 0,
    "buckets" : [
      {
        "key" : "张三",
        "doc_count" : 3
      },
      {
        "key" : "李四",
        "doc_count" : 6
      }
    ]
  }
}

2. 根据名称和级别统计数量

GET order/_search
{
  "_source": false,
  "aggs": {
    "aggs_name": {
      "multi_terms": {
        "terms": [
          {
            "field": "name.keyword"
          },
          {
            "field": "level.keyword"
          }
        ]
      }
    }
  }
}

3. 根据名称分组,再根据价格区间分组,然后统计数量

GET order/_search
{
  "_source": false,
  "aggs": {
    "aggs_name": {
      "terms": {
        "field": "name.keyword"
      },
      "aggs": {
        "aggs_price_count": {
          "range": {
            "field": "price",
            "ranges": [
              {
                "from": 1000,
                "to": 3000
              },{
                "from": 3000
              }
            ]
          }
        }
      }
    }
  }
}

  4. 根据名称分组,然后取各组的最大值,然后取各组最大值的平均值

GET order/_search
{
  "_source": false,
  "aggs": {
    "aggs_term": { // 桶聚合分组
      "terms": {
        "field": "name.keyword"
      },
      "aggs": {
        "aggs_max_price": {  // 指标聚合取最大值
          "max": {
            "field": "price"
          }
        }
      }
    },
    "pip_avg":{ // 管道聚合求最大值的平均值
      "avg_bucket": {
        "buckets_path": "aggs_term>aggs_max_price" 
        // 取值的桶的路径地址 >也可以用.代替:aggs_term.aggs_max_price
      }
    }
  }
}

5. 多个指标聚合查询,stats是max,min,avg,sum,count合并的查询语法

GET order/_search
{
  "_source": false,
  "aggs": {
    "aggs_term": {
      "terms": {
        "field": "name.keyword"
      },
      "aggs": {
        "aggs_max_price": {
          "max": {
            "field": "price"
          }
        },
        "aggs_avg_price": {
          "avg": {
            "field": "price"
          }
        },
        "aggs_all": {
          "stats": {
            "field": "price"
          }
        }
      }
    }
  }
}
查询结果:
"buckets" : [
  {
    "key" : "name1",
    "doc_count" : 3,
    "aggs_avg_price" : {
      "value" : 2000.0
    },
    "aggs_max_price" : {
      "value" : 3000.0
    },
    "aggs_all" : {
      "count" : 3,
      "min" : 1000.0,
      "max" : 3000.0,
      "avg" : 2000.0,
      "sum" : 6000.0
    }
  },
  {
    "key" : "name2",
    "doc_count" : 3,
    "aggs_avg_price" : {
      "value" : 3666.6666666666665
    },
    "aggs_max_price" : {
      "value" : 6000.0
    },
    "aggs_all" : {
      "count" : 3,
      "min" : 2000.0,
      "max" : 6000.0,
      "avg" : 3666.6666666666665,
      "sum" : 11000.0
    }
  }
]

你可能感兴趣的:(Elasticsearch,elasticsearch,大数据,搜索引擎)