BaseService.java 2.01 KB
package com.yoho.search.common;

import com.yoho.search.base.utils.ConvertUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.List;
import java.util.Map;

/**
 * Created by wangnan on 2016/12/16.
 */
public class BaseService {

    /**
     * 增加一个termsQuery
     */
    protected void boolQueryTermsQuery(Map<String, String> paramMap, BoolQueryBuilder boolFilter, String fieldName) {
        if (paramMap.containsKey(fieldName) && StringUtils.isNotBlank(paramMap.get(fieldName))) {
            List<Integer> values = ConvertUtils.stringToIntList(paramMap.get(fieldName), ",");
            if (values == null || values.isEmpty()) {
                return;
            }
            boolFilter.must(QueryBuilders.termsQuery(fieldName, values));
        }
    }

    /**
     * 增加一个termQuery
     */
    protected void boolQueryTermQuery(Map<String, String> paramMap, BoolQueryBuilder boolFilter, String fieldName) {
        if (paramMap.containsKey(fieldName) && StringUtils.isNotBlank(paramMap.get(fieldName))) {
            boolFilter.must(QueryBuilders.termQuery(fieldName, paramMap.get(fieldName)));
        }
    }

    /**
     * 批量增加termQuery
     */
    protected void addTermQueryBatch(Map<String, String> paramMap, BoolQueryBuilder boolFilter, List<String> paramsList) {
        if (CollectionUtils.isEmpty(paramsList)) {
            return;
        }
        paramsList.stream().forEach(p -> {
            if (paramMap.containsKey(p) && StringUtils.isNotBlank(paramMap.get(p))) {
                boolFilter.must(QueryBuilders.termQuery(p, paramMap.get(p)));
            }
        });
    }

    protected int getPage(Map<String, String> paramMap) {
        int page = StringUtils.isBlank(paramMap.get("page")) ? 1 : Integer.parseInt(paramMap.get("page"));
        return page;
    }
}