CodexBloom - Programming Q&A Platform

Elasticsearch 8.5 Not Returning Expected Results for Query with Multiple Aggregations on Subfields

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-16
elasticsearch aggregation nested json

I'm integrating two systems and I'm working on a personal project and I'm stuck on something that should probably be simple... I am encountering an issue with Elasticsearch 8.5 where a query with multiple aggregations on subfields is not returning the expected results. I have a dataset that includes documents representing products, with nested fields for attributes such as brand and category. The structure looks like this: ```json { "product_id": "12345", "name": "Sample Product", "attributes": [ { "brand": "BrandA", "category": "Category1", "price": 100 }, { "brand": "BrandB", "category": "Category2", "price": 150 } ] } ``` I am trying to run a query that should provide the average price of products grouped by brand and category. Here’s the query I constructed: ```json { "query": { "match_all": {} }, "aggs": { "by_brand": { "terms": { "field": "attributes.brand" }, "aggs": { "by_category": { "terms": { "field": "attributes.category" }, "aggs": { "avg_price": { "avg": { "field": "attributes.price" } } } } } } } } ``` However, this query returns an empty result set without any errors. I’ve confirmed that documents exist in the index that match the criteria. I've tried using different field names and also looked into whether the nested mapping might be causing issues, but so far, nothing has helped. I’ve also validated the mappings and can confirm that `attributes` is correctly defined as a nested type: ```json "attributes": { "type": "nested", "properties": { "brand": { "type": "keyword" }, "category": { "type": "keyword" }, "price": { "type": "double" } } } ``` To troubleshoot, I used a simpler aggregation query focusing solely on the brand without nesting, and that worked fine. Are there any specific configurations or best practices I might be overlooking for nested aggregations? What could be causing my query to return empty results? Any help would be greatly appreciated! For context: I'm using Json on macOS. I'd really appreciate any guidance on this. My team is using Json for this application.