4

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
                    }
                }
            }
        }
    }
}
Berry Blue
  • 15,330
  • 18
  • 62
  • 113

1 Answers1

7

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
          }
        }
      }
    }
  }
}
Andrei Stefan
  • 51,654
  • 6
  • 98
  • 89