ProgLearner ProgLearner - 1 month ago 5
ASP.NET (C#) Question

Elastic search combine aggregations

Currently query below removes duplicates on a single field - "name", but we need top_hits results for all fields:"name", "venueName", "venueTown". Is this possible to achieve within one query without sending 3 requests and setting "field" to be "venueName" and "venueTown"?

{
"aggs": {
"query": {
"terms": {
"field": "name"
}
,
"aggs": {
"top": {
"top_hits": {
"size": 1
}
}
}
}
},
"size": 0,
"query": {

"multi_match": {
"query": "LAURA",
"operator": "OR",
"fields": [
"name",
"venueName",
"venueTown"
]
}
}
}

Answer

If I understand correctly, you can write multiple aggregations with top hits.

{
  "query": {
    "multi_match": {
      "query": "LAURA",
      "fields": [
        "name",
        "venueName",
        "venueTown",
      ]
    }
  },
  "aggs": {
    "name": {
      "terms": {
        "field": "name"
      },
      "aggs": {
        "top": {
          "top_hits": {
            "size": 1
          }
        }
      }
    },
    "venue_name": {
      "terms": {
        "field": "venueName"
      },
      "aggs": {
        "top": {
          "top_hits": {
            "size": 1
          }
        }
      }
    },
    "venue_town": {
      "terms": {
        "field": "venueTown"
      },
      "aggs": {
        "top": {
          "top_hits": {
            "size": 1
          }
        }
      }
    }
  }
}