# 平均值聚合(Avg Aggregation)

single-value计量聚合操作就是从聚合文本中提取的数据进行求平均数的操作。这些值可以是从文本具体的数值属性中提取的值，也可以是使用脚本生成的。

假设这个数据都是有学生的考试成绩（0-100）的文档组成：

```
{
    "aggs" : {
        "avg_grade" : { "avg" : { "field" : "grade" } }
    }
}
```

上面的聚合操作就是计算所有文档的平均值。这个聚合操作的类型是avg，并且使用field来定义要计算文档中的属性。如下所示：

```
{
    ...

    "aggregations": {
        "avg_grade": {
            "value": 75
        }
    }
}
```

聚合操作的名可以也可以作为聚合操作返回的关键字（例如上面的avg）。

## Script

使用脚本计算平均值：

```
{
    ...,

    "aggs" : {
        "avg_grade" : {
            "avg" : {
                "script" : {
                    "inline" : "doc['grade'].value",
                    "lang" : "painless"
                }
            }
        }
    }
}
```

将会解释script参数作为无并发脚本语言和无脚本参数的内联脚本。一个文件脚本中包含如下参数和语法规范：

```
{
    ...,

    "aggs" : {
        "avg_grade" : {
            "avg" : {
                "script" : {
                    "file": "my_script",
                    "params": {
                        "field": "grade"
                    }
                }
            }
        }
    }
}
```

> 在索引脚本文件中可以使用id参数取代file参数。

## Value Scripts

事实证明考试是高于学生的水平的需要对学生的成绩进行校对。我们可以使用下面的脚本获取新的平均数：

```
{
    "aggs" : {
        ...

        "aggs" : {
            "avg_corrected_grade" : {
                "avg" : {
                    "field" : "grade",
                    "script" : {
                        "lang": "painless",
                        "inline": "_value * params.correction",
                        "params" : {
                            "correction" : 1.2
                        }
                    }
                }
            }
        }
    }
}
```

## Missing Value

这个missing参数就是定义文档怎样处理缺省的文档。默认情况下，它们会被忽略，也可以视它们为具体指。

```
{
    "aggs" : {
        "grade_avg" : {
            "avg" : {
                "field" : "grade",
                "missing": 10
            }
        }
    }
}
```

在文档中，如果grade这个属性没有的值话，就会默认为10.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/elasticsearch/ji-chu/36aggregationsju-he-fen-679029/liang-du-ju-540828-metric-aggregations/ping-jun-zhi-ju-540828-avg-aggregation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
