VitalyT
VitalyT

Reputation: 1691

Elasticsearch how count values from multiple document fields using aggregation

Suppose I have a lot of documents in the same index as following:

     "_source": {
            "customerId": "100",
            "firstName": "XAaa",
            "lastName": "XBbb",
            "price": 10,
            "revenue": 5
         }

     "_source": {
            "customerId": "100",
            "firstName": "XAaa",
            "lastName": "XBbb",
            "price": 20,
            "revenue": 15
        } 

    "_source": {
            "customerId": "200",
            "firstName": "YAaa",
            "lastName": "yBbb",
            "price": 110,
            "revenue": 20
       }....

Question

How make elasticsearch aggregation that count values from same customerId ??

Result should be something like:

          "_source": {
                "customerId": "100",
                "firstName": "XAaa",
                "lastName": "XBbb",
                "price": 30, // (10+20)
                "revenue": 20 //(5+15)
            } 

        "_source": {
                "customerId": "200",
                "firstName": "YAaa",
                "lastName": "yBbb",
                "price": 110,
                "revenue": 20
           }....

Thanks

Upvotes: 2

Views: 634

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

{
  "size": 0, 
  "aggs": {
    "per_customer": {
      "terms": {
        "field": "customerId",
        "size": 10
      },
      "aggs": {
        "total_price": {
          "sum" : { "field" : "price" }
        },
        "total_revenue": {
          "sum" : { "field" : "revenue" }
        }
      }
    }
  }
}

Upvotes: 1

Related Questions