Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch aggregation return multiple fields

This question is not how to do aggregation by multiple fields, which we can use sub aggregation.

If you know SQL, I can give you a perfect explanation:

SELECT SUM(SomeField1), MAX(SomeField2), MIN(SomeField3), AVG(SomeField4) FROM FooTable
GROUP BY Key1, Key2, Key3

Can we achieve that in Elasticsearch?

Thanks.

like image 607
unruledboy Avatar asked Nov 25 '25 12:11

unruledboy


1 Answers

Yes, you need to aggregate by Key1 and then add two sub-aggregations for Key2 and Key3 and finally add one metric sub-aggregation per SomeField*, basically like this:

{
  "size": 0,
  "aggs": {
    "key1": {
      "terms": {
        "field": "Key1"
      },
      "aggs": {
        "key2": {
          "terms": {
            "field": "Key2"
          },
          "aggs": {
            "key3": {
              "terms": {
                "field": "Key3"
              },
              "aggs": {
                "somefield1": {
                  "sum": {
                    "field": "SomeField1"
                  }
                },
                "somefield2": {
                  "max": {
                    "field": "SomeField2"
                  }
                },
                "somefield3": {
                  "min": {
                    "field": "SomeField3"
                  }
                },
                "somefield4": {
                  "avg": {
                    "field": "SomeField4"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
like image 61
Val Avatar answered Nov 28 '25 16:11

Val



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!