GenderAggregation.java 2 KB
package com.yoho.search.aggregations.impls;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang3.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;

public class GenderAggregation extends AbstractAggregation {

	private Map<String, String> paramMap;

	GenderAggregation(Map<String, String> paramMap) {
		this.paramMap = paramMap;
	}

	@Override
	public String aggName() {
		return "genderAgg";
	}

	@Override
	public AbstractAggregationBuilder getBuilder() {
		return AggregationBuilders.terms(aggName()).field("gender").size(10);
	}
	
	@Override
	public Object getAggregationResponseMap(Map<String, Aggregation> aggMaps) {
		MultiBucketsAggregation aggregation = this.getAggregation(aggMaps);
		if (aggregation == null) {
			return null;
		}
		Map<String, Object> genderMap = new LinkedHashMap<String, Object>();
		Iterator<? extends Bucket> itgenderAgg = aggregation.getBuckets().iterator();
		while (itgenderAgg.hasNext()) {
			Bucket ltgender = itgenderAgg.next();
			String genderId = ltgender.getKey();
			if ("1".equals(genderId)) {
				genderMap.put("1,3", "BOYS");
			} else if ("2".equals(genderId)) {
				genderMap.put("2,3", "GIRLS");
			} else {
				genderMap.put("1,3", "BOYS");
				genderMap.put("2,3", "GIRLS");
			}
		}
		if (paramMap!=null && paramMap.containsKey("gender") && StringUtils.isNotBlank(paramMap.get("gender"))) {
			String gender = paramMap.get("gender");
			if ("1,3".equals(gender) || "1".equals(gender)) {
				genderMap.put(gender, "BOYS");
			} else if ("2,3".equals(gender) || "2".equals(gender)) {
				genderMap.put(gender, "GIRLS");
			}
		}
		return genderMap;
	}

}