Home > OS >  filtering an elasticsearch query by aggregations
filtering an elasticsearch query by aggregations

Time:05-01

Hi my question is two parts. I've got a dataset that looks like

{name: "foo", 
 contracts: [{size: 1}, {size: 3}]},
{name: "bar", 
 contracts: [{size: 100}, {size: 300}]}

using the metrics aggregation I can the average size of ALL the items. 1 3 100 300 / 4, however is it possible to return the average contract size per item?

I'd like to be able to return

{name: "foo", 
 averageContract: 2}, 
{name: "bar", 
 averageContract: 200}, 

Additionally would it be possible to get that value AND filter on it?

e.g. match where averageContract > 100 ?

CodePudding user response:

Try this:

{
  "size": 0,
  "aggs": {
    "item": {
      "terms": {
        "field": "name.keyword",
        "size": 10
      },
      "aggs": {
        "averageContract": {
          "avg": {
            "field": "contracts.size"
          }
        },
        "selector_avg_contract": {
          "bucket_selector": {
            "buckets_path": {
              "avg": "averageContract"
            },
            "script": "params.avg > 100"
          }
        }
      }
    }
  }
}
  • Related