For each country / color / brand combination, find the sum of the number of items in elasticsearch

This is part of the data that I indexed in elasticsearch:

{
  "country" : "India",
  "colour" : "white",
  "brand" : "sony"
  "numberOfItems" : 3
}

I want to get the total amount numberOfItemsfor each country, per color and per brand. Is there a way to do this in elasticsearch?

+4
source share
2 answers

The following should land directly on the answer. Before use, make sure that you have included scripts.

{
  "aggs": {
    "keys": {
      "terms": {
        "script": "doc['country'].value + doc['color'].value + doc['brand'].value"
      },
      "aggs": {
        "keySum": {
          "sum": {
            "field": "numberOfItems"
          }
        }
      }
    }
  }
}
+2
source

To get one result, you can use the totality applied to a filtered query with a filter of terms (terms), for example:

{
    "query": {
        "filtered": {
            "filter": {
                "term": {
                    "country": "India"
                } 
            }
        }
    },
    "aggs": {
        "total_sum": {
            "sum": {
                "field": "numberOfItems"
            }
        }
    }
}

// , , 1 -:

{
    "query": {
        "match_all": {}
    },
    "aggs": {
        "countries": {
            "terms": {
                "field": "country"
            },
            "aggs": {
                "country_sum": {
                    "sum": {
                        "field": "numberOfItems"
                    }
                }
            }
        },
        "colours": {
            "terms": {
                "field": "colour"
            },
            "aggs": {
                "colour_sum": {
                    "sum": {
                        "field": "numberOfItems"
                    }
                }
            }
        },
        "brands": {
            "terms": {
                "field": "brand"
            },
            "aggs": {
                "brand_sum": {
                    "sum": {
                        "field": "numberOfItems"
                    }
                }
            }
        }
    }
}
0

All Articles