elasticsearch calculate average of unique values

。_饼干妹妹 提交于 2021-01-29 01:31:35

问题


How can I dynamically calculate the average of unique values in 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" }

In the above data, how can I get the unique values of the "color" field and then the averages for each of the unique "color" fields?


回答1:


Using a terms aggregation to figure out the unique color values and then an avg sub-aggregation would do the trick:

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



回答2:


Using Aggregration,you can get your answer:

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


来源:https://stackoverflow.com/questions/35480358/elasticsearch-calculate-average-of-unique-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!