1

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?

user3658423
  • 1,904
  • 5
  • 29
  • 49

2 Answers2

4

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"
          }
        }
      }
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • How to sum each field after finding average by unique field? – Hemant Sah Jan 25 '22 at 05:27
  • @HemantSah please feel free to ask a new question as yours is different than this one – Val Jan 25 '22 at 05:56
  • Thankyou, would you please see my question: https://stackoverflow.com/questions/70844178/find-average-based-on-unique-field-and-then-sum-it-up-elasticsearch – Hemant Sah Jan 25 '22 at 06:18
0

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"
                   }
                 }
               }
              }
             }
           }
krishna kumar
  • 1,190
  • 12
  • 14