This is data:
{
"search_product_sku" : "FD0044S",
"price" : 500.00,
"car_detail" : [
{
"car_brand" : "TOYOTA",
"specification" : "TOYOTA Avanza 1.3L F601 2004"
},
{
"car_brand" : "SUZUKI",
"specification" : "SUZUKI APV 1.6L GC416X8A 2005"
}
],
}
I want to nest car_detail.specification
inside car_detail.car_brand
this is nested aggregation query:
GET /my_products/_search
{
"size": 50,
"query": {
"bool": {
"must":[
{
"query_string": {
"query": "*FD0044S*",
"fields": [ "search_product_sku"]
}
}
]
}
},
"aggs": {
"total_car_brand" : {
"terms":
{
"field": "car_detail.car_brand.keyword"
},
"aggs": {
"total_car_spec": {
"terms": {
"field": "car_detail.specification.keyword"
}
}
}
}
}
}
But the results as you can see all car_detail.specification
are placed inside each car_detail.car_brand
"aggregations" : {
"total_car_brand" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "SUZUKI",
"doc_count" : 1,
"total_car_spec" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "SUZUKI APV 1.6L GC416X8A 2005",
"doc_count" : 1
},
{
"key" : "TOYOTA Avanza 1.3L F601 2004",
"doc_count" : 1
}
]
}
},
{
"key" : "TOYOTA",
"doc_count" : 1,
"total_car_spec" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "SUZUKI APV 1.6L GC416X8A 2005",
"doc_count" : 1
},
{
"key" : "TOYOTA Avanza 1.3L F601 2004",
"doc_count" : 1
}
]
}
}
]
}
}
This is a result that I want.
"aggregations" : {
"total_car_brand" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "SUZUKI",
"doc_count" : 1,
"total_car_spec" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "SUZUKI APV 1.6L GC416X8A 2005",
"doc_count" : 1
}
]
}
},
{
"key" : "TOYOTA",
"doc_count" : 1,
"total_car_spec" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "TOYOTA Avanza 1.3L F601 2004",
"doc_count" : 1
}
]
}
}
]
}
}
CodePudding user response:
I don't know how your mapping is but I tested it like this and it worked.
Mapping
PUT idx_nested
{
"mappings": {
"properties": {
"search_product_sku": {
"type": "text"
},
"price": {
"type": "integer"
},
"car_detail": {
"type": "nested",
"properties": {
"car_brand": {
"type": "keyword"
},
"specification": {
"type": "keyword"
}
}
}
}
}
}
Query
GET /idx_nested/_search
{
"size": 0,
"aggs": {
"car_detail": {
"nested": {
"path": "car_detail"
},
"aggs": {
"total_car_brand": {
"terms": {
"field": "car_detail.car_brand",
"size": 10
},
"aggs": {
"total_car_spec": {
"terms": {
"field": "car_detail.specification"
}
}
}
}
}
}
}
}