我是靠谱客的博主 虚拟蚂蚁,这篇文章主要介绍ES官网reference翻译文章(21)—Sum Aggregation求和聚合,现在分享给大家,希望可以做个参考。

对ES官网的reference的翻译,同时也是备忘,ES版本为7.5

下面是正文翻译,附上原文链接:

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html

==================================================================================================

求和聚合

单值指标聚合,对从聚合的文档中提取出来的数值进行求和。这些数值可以从文档中特定的数值字段中提取也可以从给定的脚本中生成。

假设数据由表示销售记录的文档组成,我们可以计算所有帽子的销售价格的和:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
curl -XPOST http://host_ip:host_port/sales/_search?pretty -H 'content-type: application/json'' -d '{ "size": 0, "query": { "constant_score": { "filter": { "match": { "type": "hat" } } } }, "aggs": { "hat_prices": { "sum": { "field": "price" } } } }'

返回的响应:

复制代码
1
2
3
4
5
6
7
8
{ ... "aggregations": { "hat_prices": { "value": 450.0 } } }

聚合的名称(这里的hat_prices)也能作为从返回的响应中提取除聚合结果的key。

脚本

我们也可以使用脚本来取销售价格: 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
curl -XPOST http://host_ip:host_port/sales/_search?pretty -H 'content-type: application/json'' -d '{ "size": 0, "query": { "constant_score": { "filter": { "match": { "type": "hat" } } } }, "aggs": { "hat_prices": { "sum": { "script": "doc.price.value" } } } }'

 上面的请求会使用painless脚本语言编写的无参数的脚本,为了使用保存的脚本(我理解是脚本文件,id就是文件名),使用下面的请求:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
curl -XPOST http://host_ip:host_port/sales/_search?pretty -H 'content-type: application/json'' -d '{ "size": 0, "query": { "constant_score": { "filter": { "match": { "type": "hat" } } } }, "aggs": { "hat_prices": { "sum": { "script": { "id": "my_script", "params": { "field": "price" } } } } } }'

值脚本

 我们也可以通过使用_value来获取脚本中的字段值。例如,下面的例子会计算所有帽子的价格的平方和:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
curl -XPOST http://host_ip:host_port/sales/_search?pretty -H 'content-type: application/json'' -d '{ "size": 0, "query": { "constant_score": { "filter": { "match": { "type": "hat" } } } }, "aggs": { "square_hats": { "sum": { "field": "price", "script": { "source": "_value*_value" } } } } }'

缺失的值

missing参数定义了缺失某些值的文档应该如何处理。默认的,这些文档会被忽略但我们也能把这些文档当作有值来处理。例如,下面的例子会将没有价格的帽子销售额当作100

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
curl -XPOST http://host_ip:host_port/sales/_search?pretty -H 'content-type: application/json'' -d '{ "size": 0, "query": { "constant_score": { "filter": { "match": { "type": "hat" } } } }, "aggs": { "hat_prices": { "sum": { "field": "price", "missing": 100 } } } }'

 

最后

以上就是虚拟蚂蚁最近收集整理的关于ES官网reference翻译文章(21)—Sum Aggregation求和聚合的全部内容,更多相关ES官网reference翻译文章(21)—Sum内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(66)

评论列表共有 0 条评论

立即
投稿
返回
顶部