es-aggs-api

es 聚合的api.

  • 准备数据:准备城市表的数据

  • 推送到 es.

  • java 代码

简单的将 city 表 推送到 es

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Autowired
private CityMapper cityMapper;

@Autowired
private RestClient restClient;

public void pushCityToEs(){
List<JSONObject> cityList = cityMapper.getAllCity();
for (JSONObject jsonObject : cityList) {
jsonObject.put("price", Math.random()*100);
String id = jsonObject.getString("id");
Request request = new Request("put","/city/_doc/" + id);
request.setJsonEntity(jsonObject.toJSONString());
try {
restClient.performRequest(request);
} catch (IOException e) {
e.printStackTrace();
}
}
}

metrics aggregations 聚合指标

avg

“size”: 0 表示 只要聚合的结果

对 price 求平均值。

script 里面表示 _value * correction 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
POST /city/_search
{
"size": 0,
"query": {
"match_all": {}
},
"aggs": {
"avg_price": {
"avg": {
"field": "price",
"script": {
"lang": "painless",
"source": "_value * params.correction",
"params": {
"correction": 1.2
}
}
}
}
}
}

The missing parameter defines how documents that are missing a value should be treated. By default they will be ignored but it is also possible to treat them as if they had a value.

es 官网的例子

1
2
3
4
5
6
7
8
9
10
11
POST /exams/_search?size=0
{
"aggs" : {
"grade_avg" : {
"avg" : {
"field" : "grade",
"missing": 10
}
}
}
}

weighted avg

todo

加权平均值,但是感觉不一样。后期更新。

cardinality

基数统计。但是不准确

1
2
3
SELECT parent_id
from city
GROUP BY parent_id

extend stats

A multi-value metrics aggregation 多值度量聚合

geo bounds

city(index) 增加一个字段,字段类型为: geo_point

1
2
3
4
5
6
7
8
PUT /city/_mapping
{
"properties": {
"location": {
"type": "geo_point"
}
}
}

然后推送数据上去之后,location 类型就变成了 text ,不是 geo_point 了。

参考:https://www.cnblogs.com/fanhaobai/p/7435073.html

todo

Max/Min/Sum

1
2
3
4
5
6
7
8
9
10
POST /city/_search?size=0
{
"aggs": {
"max_id": {
"max": {
"field": "id"
}
}
}
}

stats

top_hits

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
POST /city/_search?size=0
{
"aggs": {
"top_price_three": {
"top_hits": {
"sort": [
{
"price": {
"order": "desc"
}
}
],
"size": 5,
"_source": {
"includes": ["name","id"]
}
}
}
}
}

value ocunt

1
2
3
4
5
6
7
8
9
10
11
POST /city/_search?size=0
{
"aggs": {
"level_count": {
"value_count": {
"field": "parent_id"
}

}
}
}
Look at your mood.