Home > front end >  Is it possible in elastic search to retrieve several avg in one request
Is it possible in elastic search to retrieve several avg in one request

Time:11-26

I have a list of test_entry, all of them have a "name". I would like to make an avg for all of them. What I have achieved so far is to do make a request for every "name" that I have. But as you can guess, it give me performance issues (because I need to make a request for every "name")

POST test_entry/_search
{     
    "query": {  
      "bool": { 
      "must": [
        { "match": { "name": "name1" }}

      ],
        "filter": [ 
        { "range": { "Timestamp": {
        "lte":"now/d"
        }}     
        }
      ]
      }
    },  
 "size":0,
      "aggs": {
        "DoAvg": {
          "avg": {
            "field": "DO"
          }
          
        }
      }
}

this query will give me that result :

  "aggregations" : {
    "DoAvg" : {
      "value" : 7.037004702415825
    }
  }

What I would like to do is to not constrained the request to one name but having the results separated by name in the avg. the results will look like that :

  "aggregations" : {
    "DoAvg" : {
      "name1"{
      "value" : 7.03
       },
       "name2"{
       "value" : 8.33
       }
    }
  }

or even better, like that :

  "aggregations" : {
    "DoAvg" : {
      "value" : 7.03,
      "name" : "name1"
    },
    "DoAvg" : {
      "value" : 8.33,
      "name" : "name2"
    }
  }

Is this even possible ?

CodePudding user response:

You probably need sub-aggregations:

"aggs": {
  "DoAvg": {
    "terms": {
      "field": "name"
    },
    "aggs": {
      "average": {
        "avg": {
          "field": "DO"
        }
      }
    }
  }
}

If you expect more than 10 names to be returned, you should provide size to the terms aggregation.

  • Related