AgeLevelAggregation.java 2.7 KB
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;
	}

}