提取测试文档
POST test_shaheer/_doc
{
"date": "2021-03-08",
"transactionId": 2391,
"brandId": 1112,
"outletId": 121222,
"variantId": 1321,
"qty": 1,
"closing": 10,
"type": "out"
}
POST test_shaheer/_doc
{
"date": "2021-03-08",
"transactionId": 2391,
"brandId": 1112,
"outletId": 121222,
"variantId": 1321,
"qty": 1,
"closing": 10,
"type": "out"
}
POST test_shaheer/_doc
{
"date": "2021-03-08",
"transactionId": 2391,
"brandId": 1112,
"outletId": 121222,
"variantId": 1321,
"qty": 5,
"closing": 10,
"type": "in"
}
POST test_shaheer/_doc
{
"date": "2021-03-08",
"transactionId": 2391,
"brandId": 1112,
"outletId": 121222,
"variantId": 1321,
"qty": 2,
"closing": 10,
"type": "in"
}
要实现您需要的嵌套 aggregations ,首先您按 variantId 分组,然后按类型对每个 variantId 进行分组,最后对每种类型内的 qty 字段进行求和。
查询
POST test_shaheer/_search
{
"size": 0,
"aggs": {
"variant_ids": {
"terms": {
"field": "variantId",
"size": 10
},
"aggs": {
"types": {
"terms": {
"field": "type.keyword",
"size": 10
},
"aggs": {
"qty_sum": {
"sum": {
"field": "qty"
}
}
}
}
}
}
}
}
注意大小为 0 以不显示结果。
回应
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 4,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"variant_ids" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : 1321,
"doc_count" : 4,
"types" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "in",
"doc_count" : 2,
"qty_sum" : {
"value" : 7.0
}
},
{
"key" : "out",
"doc_count" : 2,
"qty_sum" : {
"value" : 2.0
}
}
]
}
}
]
}
}
}