AWS Elasticsearch 的聚合操作可以通过使用 Elasticsearch 的聚合 API 来实现。以下是一个示例,用于在 Elasticsearch 中聚合数据。
POST /sales/_search?size=0
{
"query": {
"match_all": {}
},
"aggs": {
"group_by_country": {
"terms": {
"field": "country.keyword"
},
"aggs": {
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
上述代码将在 Elasticsearch 的 “sales” 索引中对数据进行聚合。 它通过使用聚合 API 中提供的“terms” 聚合来对数据进行分组,以便按“country” 字段对数据进行分组。还使用 Elasticsearch 的 AVG 函数来计算每个分组中的“price” 字段的平均值。
注意,在聚合查询结果中只会返回聚合结果,而不是文档本身。可以使用 Ealsticsearch 的 “size” 参数来限制返回结果的数量。
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 0.0,
"hits": []
},
"aggregations": {
"group_by_country": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "CA",
"doc_count": 2,
"avg_price": {
"value": 120.0
}
},
{
"key": "US",
"doc_count": 1,
"avg_price": {
"value": 200.0
}
}
]
}
}
}