elasticsearch 去重求和
时间: 2023-07-10 21:32:48 浏览: 151
如果你想在 Elasticsearch 中对一个字段进行去重求和的话,可以使用聚合(Aggregation)功能。具体的实现步骤如下:
1. 创建一个索引并插入数据,例如:
```
PUT my_index/_doc/1
{
"name": "Alice",
"age": 25,
"salary": 5000
}
PUT my_index/_doc/2
{
"name": "Bob",
"age": 30,
"salary": 8000
}
PUT my_index/_doc/3
{
"name": "Alice",
"age": 27,
"salary": 6000
}
```
2. 使用聚合功能进行去重求和,例如:
```
POST my_index/_search
{
"size": 0,
"aggs": {
"unique_names": {
"terms": {
"field": "name"
},
"aggs": {
"total_salary": {
"sum": {
"field": "salary"
}
}
}
}
}
}
```
这个聚合查询会对 `name` 字段进行去重,然后对每个不同的名字进行求和,得到每个名字对应的总工资。执行结果如下:
```
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"aggregations": {
"unique_names": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "Alice",
"doc_count": 2,
"total_salary": {
"value": 11000
}
},
{
"key": "Bob",
"doc_count": 1,
"total_salary": {
"value": 8000
}
}
]
}
}
}
```
这个结果表明,Alice 的总工资是 11000,Bob 的总工资是 8000。
阅读全文