How can I change my query from _msearch to _search using the bucket aggregation?

Hello, I am new to Elasticsearch.

Does anybody have an idea on how to change this query from an
currently _msearch query to an _search query? It would also be convenient if I didn't have to make a separate query for every "CAR" but instead solve it with only one query. I would like to use the bucket aggregation instead.
This is my the query where I search for every Car separately:

GET /index/_msearch
{}
{"query": {"match": {"name": "CAR_RED"}},"size": 1,"sort": {"time":{"order": "desc"}}}
{}
{"query": {"match": {"name": "CAR_BLACK"}},"size": 1,"sort": {"time":{"order": "desc"}}}
{}
{"query": {"match": {"name": "CAR_WHITE"}},"size": 1,"sort": {"time":{"order": "desc"}}}

At the moment I am trying to solve it with the bucket aggregation but I always get an error.

GET /index/_search
{
  "size": 0,
    "aggs" : {
      "CARS":{
        "terms":{"field":"name.keyword"}
      },
      "bucket_sort": {
        "sort": [
        {"time":{"order": "desc"}}
        ],
        "size": 1
      }
    }
  }

It would be awesome if anyone could help me with this query.

Hi,

You need top_hits aggregation as sub-aggregation for terms aggregation.

{
 	"size": 0,
   	"aggs" : {
		"CARS":{
			"terms":{
				"field":"name.keyword"
			},
			"aggs":{
				"latest":{
					"top_hits":{
						"sort":[
							{
								"time": {"order": "desc"}
							}
						],
						"size": 1
					}
				}
			}
		}
	}
}
1 Like

Thank you :slight_smile:

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.