# 最小值聚合(Min Aggregation)

最小值聚合是一个单值度量聚合，用来记录和返回从聚合的文档中提取出的数字型值中的最小值。这些值可以从文档中的特定数字类型的字段提取，也可以通过脚本生成。

提示：最小值聚合和最大值聚合以数据的双重表示方式进行操作。 因此，如果在绝对值大于2 ^ 53的long类型的字段上运行最大值聚合或者最小值聚合，结果可能是近似值。

计算所有文档中价格最低的文档：

```
POST /sales/_search?size=0
{
    "aggs" : {
        "min_price" : { "min" : { "field" : "price" } }
    }
}
```

返回值：

```
{
    ...
    "aggregations": {
        "min_price": {
            "value": 10.0
        }
    }
}
```

可以看出，可以以聚合的名称（min\_price）作为关键字从返回的结果中查询出聚合的结果。

## script

最小值聚合也可以通过脚本来计算，下面是一个计算最低价格的脚本的例子：

```
POST /sales/_search
{
    "aggs" : {
        "min_price" : {
            "min" : {
                "script" : {
                    "inline" : "doc.price.value"
                }
            }
        }
    }
}
```

这会使用[Painless](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-painless.html) 脚本语言，而且这个脚本没有参数。如果想使用脚本文件，用下面的这种方式：

```
POST /sales/_search
{
    "aggs" : {
        "min_price" : {
            "min" : {
                "script" : {
                    "file": "my_script",
                    "params": {
                        "field": "price"
                    }
                }
            }
        }
    }
}
```

> 提示：索引脚本只需要将file参数替换为id参数。

## Value Script

比如index中的文档里的价格是以美元为单位的，但是我们现在想获得欧元的最小值（在这里假设汇率是1.2）。我们可以使用value script在聚合前来来实现每个值的汇率转化：

```
POST /sales/_search 
{ 
    "aggs" : { 
        "min_price_in_euros" : { 
            "min" : { 
                "field" : "price", 
                "script" : { 
                    "inline" : "_value * params.conversion_rate", 
                    "params" : { 
                        "conversion_rate" : 1.2 
                    } 
                } 
            } 
        } 
    } 
}
```

## Missing Value

missing参数定义了如何处理缺少值的文档。 默认情况下如果没有指定的字段，这种文档将被忽略，但也可以认为它们具有指定的值。

```
POST /sales/_search 
{ 
    "aggs" : { 
        "grade_min" : { 
            "min" : { 
                "field" : "grade", 
                "missing": 10   # 1
            } 
        } 
    } 
}
```

| 1 | 文档中如果没有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/zui-xiao-zhi-ju-540828-min-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.
