如何在 Elasticsearch 中的"group by"聚合中进行总和聚合?



你好:(我们需要一些关于ElasticSearch查询的帮助

因此,我们有以下映射:

"document" : {
"properties" : {
"client" : {
"type" : "keyword",
"fields" : {
"client_search" : {
"type" : "text",
"analyzer" : "eflow_nGram_analyzer"
}
},
"normalizer" : "ci_normalizer"
},
"postings" : {
"type" : "nested",
"include_in_parent" : true,
"properties" : {
"amount" : {
"type" : "double",
"fields" : {
"amount_search" : {
"type" : "text",
"analyzer" : "eflow_nGram_analyzer"
}
}
},
"product" : {
"properties" : {
"client" : {
"type" : "keyword",
"normalizer" : "ci_normalizer"
},
"cost" : {
"type" : "double",
"fields" : {
"cost_search" : {
"type" : "text",
"analyzer" : "eflow_nGram_analyzer"
}
}
},
"description" : {
"type" : "text"
},
"rno" : {
"type" : "keyword",
"normalizer" : "ci_normalizer"
},
}
},
"quantity" : {
"type" : "double",
"fields" : {
"quantity_search" : {
"type" : "text",
"analyzer" : "eflow_nGram_analyzer"
}
}
},

文档->嵌套发布->产品、数量、

该产品有一个id(rno(,成本描述。

我想做的是按产品ID对文档进行分组并添加数量。

例如,如果我有两个文档,文档A和文档B

单据A有两个过账:

  1. 发布数量为1的1和数量为rno X的产品
  2. 张贴数量为4的2和数量为rno Y的产品

单据B有两个过账:

  1. 发布数量为1的1和数量为rno X的产品
  2. 张贴数量为3的2和数量为rno Z的产品

我想按product.rno分组,只对按product-rno分组的帖子中的数量求和。

所以我想要:

  1. 产品rno X和总量为1+1=2的组
  2. 产品编号为rno Y,总数量为4的组
  3. 产品编号为rno Z,总数量为3的组

我有以下聚合:

"aggs": {
"group_by_product_id": {
"terms": {
"field": "document.postings.product.rno"
},
"aggs": {
"product_quantity_total": {
"sum": {
"field": "document.postings.quantity"
}
}
}
}
}

但总数量的计算是错误的,因为它添加了来自张贴的所有数量,而不是来自rno 的组的所有数量

因此,对于上面的例子,我将获得:

  1. 产品rno X和总量为1+4+1+3=9的组
  2. 产品rno为Y且总量为4+1=5的组
  3. 产品rno Z和总量为3+1=4的组

你知道我如何使用弹性搜索按嵌套结构(document.postings.product.rno(内的字段进行分组,然后添加一个总和聚合,只对分组依据内匹配项目的字段(document.pastings.count(进行总和吗?

这与类似

聚合结构应该是这样的:

"aggs": {
"the_postings": {
"nested": {
"path": "document.postings"
},
"aggs": {
"group_by_product_id": {
"terms": {
"field": "document.postings.product.rno"
},
"aggs": {
"total_quantity": {
"sum": {
"field": "document.postings.quantity"
}
}
}
}
}
}
}

因此,你需要再浏览一层,即嵌套的帖子,以便获得与产品字段(其中你根据产品id"分组"(相同级别的数量字段的正确摘要

最新更新