elasticsearch计算唯一值的平均值

时间:2016-02-18 11:35:57

标签: elasticsearch

如何动态计算elasticsearch中唯一值的平均值?

{ "price" : 10000, "color" : "red" }
{ "price" : 20000, "color" : "red" }
{ "price" : 30000, "color" : "green" }
{ "price" : 15000, "color" : "blue" }
{ "price" : 12000, "color" : "green" }
{ "price" : 20000, "color" : "red" }
{ "price" : 80000, "color" : "red" }
{ "price" : 25000, "color" : "blue" }

在上述数据中,如何获取“颜色”字段的唯一值,然后获取每个唯一“颜色”字段的平均值?

2 个答案:

答案 0 :(得分:3)

使用terms aggregation找出唯一的颜色值然后使用avg sub-aggregation可以解决问题:

{
  "aggs": {
    "colors": {
      "terms": {
        "field": "color"
      },
      "aggs": {
        "average": {
          "avg": {
            "field": "price"
          }
        }
      }
    }
  }
}

答案 1 :(得分:0)

使用聚合,您可以得到答案:

  curl -XGET 'localhost:9200/demo/post/_search?pretty=true' -d 
     '{
    "aggs": {
      "aggs_color": {
          "terms": {
           "field": "color"
            },
     "aggs": {
       "aggs_avg": {
           "avg": {
           "field": "price"
                   }
                 }
               }
              }
             }
           }