AgeLevelAggregation.java
2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.yoho.search.aggregations.impls;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket;
import com.yoho.search.aggregations.AbstractAggregation;
import com.yoho.search.vo.AgeLevelVo;
/**
* 年龄层聚合对象
* @author hugufei
*
*/
public class AgeLevelAggregation extends AbstractAggregation {
private static Map<String, String> ageLevelMap = new LinkedHashMap<String, String>();
// 1:成人 2:大童 3:小童 4:中童 5:幼童
static{
ageLevelMap.put("1", "成人");
ageLevelMap.put("2", "大童");
ageLevelMap.put("4", "中童");
ageLevelMap.put("3", "小童");
ageLevelMap.put("5", "幼童");
}
AgeLevelAggregation(){
super();
}
@Override
public String aggName() {
return "ageLevelAgg";
}
@Override
public AbstractAggregationBuilder getBuilder() {
return AggregationBuilders.terms(aggName()).field("ageLevel").size(100);
}
@Override
public Object getAggregationResponseMap(Map<String, Aggregation> aggMaps) {
MultiBucketsAggregation aggregation = this.getAggregation(aggMaps);
if (aggregation == null) {
return null;
}
Map<String, AgeLevelVo> resultMap = new HashMap<String, AgeLevelVo>();
Iterator<? extends Bucket> itgenderAgg = aggregation.getBuckets().iterator();
while (itgenderAgg.hasNext()) {
Bucket ltgender = itgenderAgg.next();
String ageLevel = ltgender.getKey();
if (StringUtils.isBlank(ageLevel)) {
continue;
}
long count = ltgender.getDocCount();
String[] ageLevels = ageLevel.split(",");
for (String ageLevelId : ageLevels) {
if (!ageLevelMap.containsKey(ageLevelId)) {
continue;
}
AgeLevelVo ageLevelVo = resultMap.get(ageLevelId);
if (ageLevelVo == null) {
ageLevelVo = new AgeLevelVo();
resultMap.put(ageLevelId, ageLevelVo);
}
ageLevelVo.setId(ageLevelId);
ageLevelVo.setName(ageLevelMap.get(ageLevelId));
ageLevelVo.setProduct_count(ageLevelVo.getProduct_count() + count);
}
}
// 转换成队列,并按ageLevelMap的顺序排好序
List<AgeLevelVo> results = new ArrayList<AgeLevelVo>();
for (String id : ageLevelMap.keySet()) {
AgeLevelVo ageLevelVo = resultMap.get(id);
if (ageLevelVo != null) {
results.add(ageLevelVo);
}
}
return results;
}
}