Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple aggregations in Elasticsearch

I want to do a terms aggregation on two fields. I don't want a sub-aggregations but I want results in two different bucket groups like if I did two separate queries for the two fields. Is it possible to combine these two queries into one?

First query:

{
    "size" : 0,
    "aggs" : {
        "brands" : {
            "terms" : {
                "field" : "my_field1",
                "size" : 15
            },
            "aggs" : {
                "my_field_top_hits1" : {
                    "top_hits" : {
                        "size" : 1
                    }
                }
            }
        }
    }
}

Second query:

{
    "size" : 0,
    "aggs" : {
        "brands" : {
            "terms" : {
                "field" : "my_field2",
                "size" : 15
            },
            "aggs" : {
                "my_field_top_hits2" : {
                    "top_hits" : {
                        "size" : 1
                    }
                }
            }
        }
    }
}
like image 751
Berry Blue Avatar asked Sep 10 '25 19:09

Berry Blue


1 Answers

Unless I'm missing something obvious, you just need to do:

{
  "size": 0,
  "aggs": {
    "brands_field1": {
      "terms": {
        "field": "my_field1",
        "size": 15
      },
      "aggs": {
        "my_field_top_hits1": {
          "top_hits": {
            "size": 1
          }
        }
      }
    },
    "brands_field2": {
      "terms": {
        "field": "my_field2",
        "size": 15
      },
      "aggs": {
        "my_field_top_hits1": {
          "top_hits": {
            "size": 1
          }
        }
      }
    }
  }
}
like image 56
Andrei Stefan Avatar answered Sep 13 '25 11:09

Andrei Stefan