CodexBloom - Programming Q&A Platform

Unexpected Behavior with Elasticsearch Aggregation on Nested Fields in Version 8.0

๐Ÿ‘€ Views: 93 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-13
elasticsearch aggregation nested json

I'm learning this framework and I'm facing an issue when trying to perform an aggregation on nested fields in my Elasticsearch 8.0 index. I have a document structure that includes a nested field for `orders` within `customers`, and I'm trying to calculate the total amount spent by each customer. However, the aggregation seems to return incorrect totals. Hereโ€™s a sample of my document structure: ```json { "customer_id": "123", "name": "John Doe", "orders": [ { "order_id": "1", "amount": 100 }, { "order_id": "2", "amount": 150 } ] } ``` Iโ€™ve defined the mapping for my `customers` index as follows: ```json { "mappings": { "properties": { "customer_id": { "type": "keyword" }, "name": { "type": "text" }, "orders": { "type": "nested", "properties": { "order_id": { "type": "keyword" }, "amount": { "type": "double" } } } } } } ``` The aggregation query I'm using is: ```json { "size": 0, "aggs": { "total_spent": { "nested": { "path": "orders" }, "aggs": { "total_amount": { "sum": { "field": "orders.amount" } } } } } } ``` When I run the above query, it returns a total amount of `0`, even though I have two orders with amounts of `100` and `150`. I've checked the mapping and confirmed that the `amount` field is correctly set as `double`, and the index has been populated with documents. I've also tried using a `filter` aggregation to isolate specific customers, but it doesnโ€™t seem to change the outcome. Additionally, I attempted using the `filter` aggregation in conjunction with the nested aggregation, but I still get `0` as a result. What am I missing here? Is there something specific about how nested aggregations should be structured or executed that I might not be following correctly? Any insights would be appreciated!