elasticsearchHow do I use nested aggregation in Elasticsearch?
Nested aggregations in Elasticsearch allow you to aggregate data within nested objects. This can be used to answer questions such as “What are the top 5 most popular products in each category?”
Example code
GET /_search
{
"size": 0,
"aggs": {
"categories": {
"nested": {
"path": "products"
},
"aggs": {
"top_products": {
"terms": {
"field": "products.name.keyword",
"size": 5
}
}
}
}
}
}
Output example
{
...
"aggregations" : {
"categories" : {
"doc_count" : 12,
"top_products" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "Product A",
"doc_count" : 4
},
{
"key" : "Product B",
"doc_count" : 3
},
{
"key" : "Product C",
"doc_count" : 2
},
{
"key" : "Product D",
"doc_count" : 1
},
{
"key" : "Product E",
"doc_count" : 1
}
]
}
}
}
...
}
Code explanation
GET /_search
- this is the endpoint used to send the aggregation query."size": 0
- this specifies that no documents should be returned, only the aggregation results."aggs": {
- this is the start of the aggregation section."categories": {
- this is the name of the top-level aggregation."nested": {
- this specifies that the aggregation should be done within a nested object."path": "products"
- this specifies the path of the nested object."terms": {
- this specifies that the aggregation should be done using terms."field": "products.name.keyword"
- this specifies the field used for the terms aggregation."size": 5
- this specifies the number of results to return.
Helpful links
More of Elasticsearch
- How do I use Elasticsearch with ZGC?
- How can I use Elasticsearch to diagnose "yellow" issues?
- How do I set up an Elasticsearch Yum repository?
- How can I use elasticsearch zone awareness to improve my software development?
- How do I use ElasticSearch to zip files?
- How can I use Elasticsearch and ZFS together?
- How can I set up and use Elasticsearch on the Yandex Cloud platform?
- How can I use Yandex Mirror to access Elasticsearch data?
- How can I use Kibana to visualize data stored in Elasticsearch?
- How can I use Elasticsearch with Zammad?
See more codes...