unruledboy
unruledboy

Reputation: 2342

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.

Upvotes: 3

Views: 4149

Answers (1)

Val
Val

Reputation: 217554

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"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Upvotes: 8

Related Questions