Applying aggregation to query results

Hello everyone, I'm trying to apply an aggregation filter to my query, I basically have an array of objects which looks like this

{
  "productDeals": [
	{
	  "id": 1,
      "startAt": "2021-08-30T17:40:14.000Z",
	  "endAt": "2021-11-30T21:00:00.000Z",
      "createdAt": "2021-08-30T17:40:14.179Z",
	  "modifiedAt": "2021-08-30T17:40:14.179Z",
	},
	{
	  "id": 1,
      "startAt": "2021-08-30T17:40:14.000Z",
	  "endAt": "2022-10-30T21:00:00.000Z",
      "createdAt": "2021-08-30T17:40:14.179Z",
	  "modifiedAt": "2021-08-30T17:40:14.179Z",
	}
  ]
}

I'm trying to get the productDeal with the furthest endAt date, I was able to do so using this query

{
	"query": {
		"bool": {
			"should": [{
				"match": {
					"id": 10
				}
			}]
		}
	},
	"aggs": {
		"productDeals": {
			"nested": {
				"path": "productDeals"
			},
			"aggs": {
				"max_productDeals": {
					"max": {
						"field": "productDeals.endAt"
					}
				}
			}
		}
	}
}

This query works and gives the following output

{
	"product": {
		"id": 10,
		"whatever": "whatever",
		"productDeals": [{
				"id": 1,
				"startAt": "2021-08-30T17:40:14.000Z",
				"endAt": "2021-11-30T21:00:00.000Z",
				"createdAt": "2021-08-30T17:40:14.179Z",
				"modifiedAt": "2021-08-30T17:40:14.179Z"
			},
			{
				"id": 1,
				"startAt": "2021-08-30T17:40:14.000Z",
				"endAt": "2022-10-30T21:00:00.000Z",
				"createdAt": "2021-08-30T17:40:14.179Z",
				"modifiedAt": "2021-08-30T17:40:14.179Z"
			}
		]
	}
}

Then at the end it adds on this

 "aggregations" : {
    "productDeals" : {
      "doc_count" : 2,
      "max_productDeals" : {
        "value" : 1.669842E12,
        "value_as_string" : "2022-11-30T21:00:00.000Z"
      }
    }
  }
}

This is not helpful for me, instead I want to apply it to the document, I want the result to be

product: {
id....

productDeal: [
//The deal with the furthest endDate here
]
}
}

If you only need the top document, do you really need an aggregation or can you just return a single document, sorted by your endAt field?

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