如何解决带总和的聚合弹性搜索查询
这是我当前的数据。我想要一个聚合查询以根据输入/输出类型返回数量的变体 ID 总和。
hits: {
total: {
value: 5,relation: "eq",},max_score: 1,hits: [
{
_index: "transactions",_type: "_doc",_id: "out2391",_score: 1,_source: {
date: "2021-03-08",transactionId: 2391,brandId: 1112,outletId: 121222,variantId: 1321,qty: 1,closing: 10,type: "out",}
],
我想要返回输入/输出变量数量总和的结果
[{
variantId: 1321,in: sum(qty),out: sum(qty)
},{
variantId: 13211,out: sum(qty)
}
]
解决方法
提取测试文档
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","qty": 5,"type": "in"
}
POST test_shaheer/_doc
{
"date": "2021-03-08","qty": 2,"type": "in"
}
要实现您需要的嵌套 aggregations ,首先按变体 ID 分组,然后按类型对每个变体 ID 进行分组,最后对每个类型中的 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,"buckets" : [
{
"key" : "in","doc_count" : 2,"qty_sum" : {
"value" : 7.0
}
},{
"key" : "out","qty_sum" : {
"value" : 2.0
}
}
]
}
}
]
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。