Elasticsearch-麦田项目实战

jar

 

ESClient.java

package cn.maitian.newhouse.framework.search.client;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;

import cn.maitian.newhouse.framework.core.util.AppPropUtil;
import cn.maitian.newhouse.framework.core.util.AppPropUtil.Keys;
import cn.maitian.newhouse.framework.search.model.EsMethodName;
import cn.maitian.newhouse.framework.search.model.EsQueryModel;
import cn.maitian.newhouse.framework.search.model.NewHouseQueryModel;

/**
 * ElasticSearch客户端
 * 
 * @author LXINXIN
 * @company MAITIAN
 * @version 1.0
 */
public class ESClient {

    private static String esServer;

    private static String clusterName;

    private static PoolingHttpClientConnectionManager connManager = null;
    /**
     * 将最大连接数增加到
     */
    public static final int MAX_TOTAL = 200;
    /**
     * 将每个路由基础的连接增加到
     */
    public static final int MAX_ROUTE_TOTAL = 300;
    /**
     * 请求超时时间
     */
    public static final int REQUEST_TIMEOUT = 5 * 1000;
    /**
     * 请求连接超时时间
     */
    public static final int REQUEST_SOCKET_TIME = 5 * 1000;

    private static CloseableHttpClient httpclient;

    static {
        connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(MAX_TOTAL);
        connManager.setDefaultMaxPerRoute(MAX_ROUTE_TOTAL);

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(REQUEST_TIMEOUT)
                .setSocketTimeout(REQUEST_SOCKET_TIME).build();
        // 设置重定向策略
        LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();

        httpclient = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(requestConfig)
                .setRedirectStrategy(redirectStrategy).build();
        esServer = AppPropUtil.getPropValue(Keys.SEARCH_ES_SERVER);
        clusterName = AppPropUtil.getPropValue(Keys.SEARCH_ES_ClUSTER_NAME);
    }

    /**
     * 从ES服务器查询记录
     * 
     * @param index
     *            索引
     * @param type
     *            类型
     * @param pageNo
     *            页码(从1开始)
     * @param size
     *            页面大小
     * @param queryConditions
     *            查询条件MAP
     * @param rangeLists
     *            范围过滤
     * @param sortMaps
     *            排序MAP
     * @param hightLightFields
     *            高亮字段
     * @return String
     * @throws Exception
     *             抛出异常
     */
    public static String query(String index, String type, int pageNo, int size, Map<String, Object> queryConditions,
            List<Map<String, Object>> rangeLists, Map<String, Object> sortMaps, List<String> hightLightFields)
            throws Exception {

        HttpPost httpPost = new HttpPost(esServer + EsMethodName.query);
        EsQueryModel model = new EsQueryModel().setClusterName(clusterName).setQueryConditions(queryConditions)
                .setIndex(index).setType(type).setRangeFields(rangeLists).setHightLightFields(hightLightFields)
                .setPageNo(pageNo).setSortFields(sortMaps).setSize(size);
        try {
            return post(httpclient, model, httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 新房查询
     * @param queryVo
     * @return
     */
    public static String newHouseQuery(NewHouseQueryModel queryVo){
        HttpPost httpPost = new HttpPost(esServer + EsMethodName.newHouseQuery);
        EsQueryModel model = new EsQueryModel().setIndex(queryVo.getIndex()).setType(queryVo.getType())
                .setCountField(queryVo.getCountField()).setSumField(queryVo.getSumField())
                .setRangeFields(queryVo.getRangeFields()).setMust(queryVo.getMust()).setSumGroupby(queryVo.getSumGroupby())
                .setShould(queryVo.getShould()).setPageNo(queryVo.getPageNo())
                .setSortFields(queryVo.getSortMaps()).setSize(queryVo.getSize());
        try {
            return post(httpclient, model, httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 多字段查询
     * 
     * @param index
     *            索引名称
     * @param type
     *            索引类型
     * @param pageNo
     *            当前页码,从1开始
     * @param size
     *            页面数据大小
     * @param must
     *            必查的字段及值,key为字段名称,value为字段值
     * @param should
     *            非必查的字段及值
     * @param rangeLists
     *            范围过滤
     * @param sortMaps
     *            排序MAP
     * @param hightLightFields
     *            高亮字段
     * @param countField 
     *             聚合字段
     * @param  sumField
     *             求合字段           
     * @return String
     */
    public static String queryMultiFields(String index, String type, int pageNo, int size, Map<String, Object> must,
            Map<String, Object> should, List<Map<String, Object>> rangeLists, Map<String, Object> sortMaps,
            List<String> hightLightFields ) {
        HttpPost httpPost = new HttpPost(esServer + EsMethodName.queryMultiField);
        EsQueryModel model = new EsQueryModel().setClusterName(clusterName).setIndex(index).setType(type)
                .setRangeFields(rangeLists).setMust(must).setShould(should).setHightLightFields(hightLightFields)
                .setPageNo(pageNo).setSortFields(sortMaps).setSize(size);
        try {
            return post(httpclient, model, httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            String expMsg = sw.toString();
            try {
                pw.close();
                sw.close();
            } catch (Exception e2) {
            }
            throw new RuntimeException(expMsg);
        }
    }

    /**
     * 插入记录
     * 
     * @param index
     *            索引
     * @param type
     *            类型
     * @param id
     *            主键
     * @param content
     *            内容
     * @return String
     */
    public static String insert(String index, String type, String id, Map<String, Object> content) {
        HttpPost httpPost = new HttpPost(esServer + EsMethodName.insert);
        EsQueryModel model = new EsQueryModel().setIndex(index).setId(id).setType(type)
                .setContent(content);
        try {
            return post(httpclient, model, httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            String expMsg = sw.toString();
            try {
                pw.close();
                sw.close();
            } catch (Exception e2) {
            }
            throw new RuntimeException(expMsg);
        }
    }

    /**
     * 更新记录
     * 
     * @param index
     *            索引
     * @param type
     *            类型
     * @param id
     *            主键
     * @param newContent
     *            新的内容
     * @return String
     */
    public static String update(String index, String type, String id, Map<String, Object> newContent) {
        HttpPost httpPost = new HttpPost(esServer + EsMethodName.update);
        EsQueryModel model = new EsQueryModel().setClusterName(clusterName).setIndex(index).setId(id).setType(type)
                .setNewContents(newContent);
        try {
            return post(httpclient, model, httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            String expMsg = sw.toString();
            try {
                pw.close();
                sw.close();
            } catch (Exception e2) {
            }
            throw new RuntimeException(expMsg);
        }
    }

    /**
     * 根据ID删除记录
     * 
     * @param index
     *            索引
     * @param type
     *            类型
     * @param id
     *            主键
     * @return String
     */
    public static String deleteById(String index, String type, String id) {
        HttpPost httpPost = new HttpPost(esServer + EsMethodName.deleteRecordById);
        EsQueryModel model = new EsQueryModel().setClusterName(clusterName).setId(id).setType(type).setIndex(index);
        try {
            return post(httpclient, model, httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            String expMsg = sw.toString();
            try {
                pw.close();
                sw.close();
            } catch (Exception e2) {
            }
            throw new RuntimeException(expMsg);
        }
    }

    /**
     * 发送请求
     * 
     * @param client
     *            httpclient对象
     * @param model
     *            ES查询的MODEL
     * @param httpPost
     *            httpPost请求对象
     * @return 返回ES查询结果的JSON字符串
     * @throws IOException
     */
    private static String post(CloseableHttpClient client, EsQueryModel model, HttpPost httpPost) throws IOException {
        String json = JSON.toJSONString(model);
        StringEntity s = new StringEntity(json, "UTF-8");
        s.setContentEncoding("utf-8");
        s.setContentType("application/json");
        httpPost.setEntity(s);
        CloseableHttpResponse response = client.execute(httpPost);
        String txt = EntityUtils.toString(response.getEntity());
        response.close();
        return txt;
    }

    /**
     * 批量索引
     * 
     * @param index
     *            索引
     * @param type
     *            类型
     * @param contents
     *            批量索引的内容
     * @return String
     */
    public static String batchInsert(String index, String type, List<Map<String, Object>> contents) {
        HttpPost httpPost = new HttpPost(esServer + EsMethodName.batchInsert);
        EsQueryModel model = new EsQueryModel().setClusterName(clusterName).setIndex(index).setType(type)
                .setContents(contents);
        try {
            return post(httpclient, model, httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            String expMsg = sw.toString();
            try {
                pw.close();
                sw.close();
            } catch (Exception e2) {
            }
            throw new RuntimeException(expMsg);
        }
    }
    
    
    /**
     * 一手房下拉提示框用的
     * @param index    索引
     * @param type1             城市type
     * @param type2             楼盘type
     * @param size     数量
     * @param key      检索词
     * @param cityCode 城市代码
     * @return  提示框用的字符串
     */
    public static String doSuggest(String index,String type1,String type2,Integer size,String key,Integer cityCode){
        HttpPost httpPost = new HttpPost(esServer + EsMethodName.doSuggest);
        EsQueryModel model = new EsQueryModel().setIndex(index)
                  .setAreaType(type1).setStageNameType(type2).setSize(size).setCityCode(cityCode).setKey(key);
        try {
            return post(httpclient, model, httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            String expMsg = sw.toString();
            try {
                pw.close();
                sw.close();
            } catch (Exception e2) {
            }
            throw new RuntimeException(expMsg);
        }
    }

   public static String stageSuggest(String index,String type,Integer size,String key,Integer cityCode) {
       HttpPost httpPost = new HttpPost(esServer + EsMethodName.stageSuggest);
        EsQueryModel model = new EsQueryModel().setIndex(index)
                  .setType(type).setSize(size).setCityCode(cityCode).setKey(key);
        try {
            return post(httpclient, model, httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            String expMsg = sw.toString();
            try {
                pw.close();
                sw.close();
            } catch (Exception e2) {
            }
            throw new RuntimeException(expMsg);
        }
   }
}

AppPropUtil.java

package cn.maitian.newhouse.framework.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import cn.maitian.newhouse.framework.core.exception.AppSysException;

/**
 * Java Properties 文件操作
 * 
 * @author LXINXIN
 * @company MAITIAN
 * @version 1.0
 */
public class AppPropUtil {

    /**
     * 配置文件名称
     */
    private static String propConfigName = "config/app-config-dev.properties";
    /**
     * 默认配置文件属性
     */
    private static Properties defaultProps;

    /**
     * 私有的构造方法
     * 
     * @param lvPropConfigPath
     *            配置文件路径
     */
    public AppPropUtil(String lvPropConfigPath) {
        AppPropUtil.propConfigName = lvPropConfigPath;
        initDefault();
    }

    /**
     * 初始化数据
     */
    private static void initDefault() {
        if (propConfigName == null || propConfigName.length() <= 0) {
            throw new AppSysException("SE900010");
        }
        defaultProps = getProperties(propConfigName);
    }

    /**
     * 获取配置文件的value
     * 
     * @param key
     *            properties的key
     * 
     * @return String
     */
    public static String getPropValue(AppPropUtil.Keys key) {
        if (defaultProps == null) {
            initDefault();
        }
        if (defaultProps == null) {
            return null;
        }
        return defaultProps.getProperty(key.toString());
    }

    /**
     * 获取配置文件的value
     * 
     * @param key
     *            properties的key
     * 
     * @return String
     */
    public static Integer getIntegerValue(AppPropUtil.Keys key) {
        String result = getPropValue(key);
        return Integer.valueOf(result);
    }

    /**
     * 获取配置文件的value
     * 
     * @param key
     *            properties的key
     * 
     * @return String
     */
    public static Long getLongValue(AppPropUtil.Keys key) {
        String result = getPropValue(key);
        return Long.valueOf(result);
    }

    /**
     * 获取配置文件的value
     * 
     * @param key
     *            properties的key
     * 
     * @return String
     */
    public static Boolean getBooleanValue(AppPropUtil.Keys key) {
        String result = getPropValue(key);
        return "true".equalsIgnoreCase(result);
    }

    /**
     * 返回文件属性
     * 
     * @param file
     *            文件名称
     * @return Properties
     */
    public static Properties getProperties(String file) {
        InputStream inStream = AppPropUtil.class.getClassLoader().getResourceAsStream(file);
        Properties result = new Properties();
        try {
            result.load(inStream);
        } catch (IOException e) {
            // TODO 修改为编码
            throw new AppSysException("文件加载失败!");
        }
        return result;
    }

    /**
     * @return the propConfigName
     */
    public static String getPropConfigName() {
        return propConfigName;
    }

    /**
     * @param propConfigName
     *            the propConfigName to set
     */
    public static void setPropConfigName(String propConfigName) {
        AppPropUtil.propConfigName = propConfigName;
    }

    /**
     * 配置文件中的key
     */
    public enum Keys {
        /**
         * 菩提固定搜索引擎查询1000条数据
         */
        BODHI_FIXED_COUNT,
        /**
         * 菩提固定搜索引擎查询基础时间
         */
        BODHI_FIXED_TIME,
        /**
         * 服务器路径
         */
        APP_SERVER_PATH,
        /**
         * 调度服务器地址
         */
        SCHEDULE_SERVER_PATH,
        /**
         * 文件上传路径前缀http
         */
        FILE_UPLOAD_HTTP,
        /**
         * 文件上传路径前缀https
         */
        FILE_UPLOAD_HTTPS,
        /**
         * 安卓文件上传路径前缀
         */
        ANDROID_UPLOAD_PREFIX,
        /**
         * IOS文件上传路径前缀
         */
        IOS_UPLOAD_PREFIX,
        /**
         * 读取文件路径前缀http
         */
        DOWNLOAD_FILE_HTTP,
        /**
         * 读取文件路径前缀https
         */
        DOWNLOAD_FILE_HTTPS,
        /**
         * 安卓下载路径
         */
        ANDROID_DEFAULT_INSTALL,
        /**
         * IOS下载路径
         */
        IOS_DEFAULT_INSTALL,
        /**
         * IOS证书下载地址
         */
        IOS_CRT,
        /**
         * 环信接口调用地址
         */
        EMCHAT_URL,
        /**
         * 环信接口调用APP_ID
         */
        APP_CLIENT_ID,
        /**
         * 环信接口调用KEY
         */
        APP_CLIENT_SECRET,
        /**
         * Kafka——boker分区的静态信息,可以多个
         */
        KAFKA_BOKER,
        /**
         * Kafka——zookeeper 配置
         */
        KAFKA_ZOOKEEPER,
        /**
         * 房源图片前缀路径
         */
        PICTURE_SERVER_OLD_IP,
        /**
         * 房源图片前缀路径
         */
        PICTURE_SERVER_IP,
        /**
         * 麦田在线分享URL
         */
        SHARE_MTONLINE_URL,
        /**
         * 搜索引擎地址
         */
        SEARCH_ES_SERVER,
        /**
         * 搜索引擎的集群名称
         */
        SEARCH_ES_ClUSTER_NAME,
        /**
         * 麦田在线图片服务器地址
         */
        MTONLINE_IMG_SERVER_URL,
        /**
         * 麦田在线H5服务器地址
         */
        MTONLINE_H5_SERVER_URL,
        /**
         * 环信消息发送控制
         */
        IS_SEND_EM,
        /**
         * 菩提每日提问上限
         */
        BODHI_PUT_QUESTION_LIMIT,
        /**
         * 运营官方邮箱
         */
        OPERATING_OFFICAIL_MAILBOX,
        /**
         * 活动中奖区间的最大值,根据上线人数计算,此值由产品定,第一期为25000
         */
        ACTIVITY_INTERVAK_MAX_VAL,

        /**
         * 在线房源检测url
         */
        MTONLINE_HOUSE_TESTING_URL,
        /**
         * 短信发送地址
         */
        SMS_URL,
        /**
         * 短信业务ID
         */
        SMS_APPID
    }

}

配置文件

#\u641c\u7d22\u5f15\u64ce\u5730\u5740
SEARCH_ES_SERVER=http://172.16.13.203:8081/EsQuery/query/
SEARCH_ES_ClUSTER_NAME=newhouse-es-dev

ESContant.java

package cn.maitian.newhouse.framework.search.client;

/**
 * 
 * @author LXINXIN
 * @company MAITIAN
 * @version 1.0
 */
public class ESContant {
    
    /**
     * suggest 索引Index
     */
    public final static String SUGGESTINDEX="newhouse";
    
    /**
     * suggest 类型area
     */
    public final static String TYPEAREA="area";
    
    /**
     * suggest 类型stagename
     */
    public final static String TYPESTAGENAME="stagename";
    
    /**
     * 存放检索数据的index
     */
    public final static String SEARCHINDEX="newhouse_search";
    
    /**
     * 存放检索数据的type
     */
    public final static String SEARCHTYPE="newhouse_type";
    
    /**
     * 存放新房报备表type
     */
    public final static String NHREPORT_TYPE="nhReport_type";
    
    /**
     * 存放新房带看type
     */
    public final static String NHREPORTSEE_TYPE="nhReportSee_type";
    
    /**
     * 存放新房空看type
     */
    public final static String NHEMPTYVISIT_TYPE="nhEmptyVisit_type";
    
    /**
     * 存放新房空看预约TYPE
     */
    public final static String NHAPPOINTMENT_TYPE="nhAppointment_type";
    
    /**
     * 业绩单type
     */
    public final static String NHSALEPERFORMANCE_TYPE="nhSalePerformance_type";
  
}

EsMethodName.java

package cn.maitian.newhouse.framework.search.model;

/**
 * 
 * @author LXINXIN
 * @company MAITIAN
 * @version 1.0
 */
public class EsMethodName {

    /**
     * 添加方法
     */
    public final static String insert = "insertRecord";
    /**
     * 更新方法
     */
    public final static String update = "updateRecord";
    /**
     * 查询方法
     */
    public final static String query = "queryDocumentsUseScroll";
    /**
     * 删除方法
     */
    public final static String deleteRecordById = "deleteRecordById";
    /**
     * 删除方法
     */
    public final static String deleteRecordsByConditions = "deleteRecordsByConditions";
    /**
     * 查询方法
     */
    public final static String queryMultiField = "queryMultiField";
    
    /**
     * 批量索引
     */
    public final static String batchInsert = "batchInsert";
    
    /**
     * 做提示
     */
    public final static String doSuggest ="doSuggest";
    
    /**
     * 新房查询
     */
    public final static String newHouseQuery = "newHouseQuery";
    
    /**
     * 搜索房子自动补全
     */
    public final static String stageSuggest ="stageSuggest";

}

EsQueryModel.java

package cn.maitian.newhouse.framework.search.model;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author LXINXIN
 * @company MAITIAN
 * @version 1.0
 */
public class EsQueryModel implements Serializable {

    private static final long serialVersionUID = 1318299673374536774L;

    /**
     * 记录主键
     */
    private String id;

    /**
     * 记录索引
     */
    private String index;
    /**
     * 记录类型
     */
    private String type;

    /**
     * 查询条件
     */
    private Map<String, Object> queryConditions;

    /**
     * 过滤范围
     */
    private List<Map<String, Object>> rangeFields;

    /**
     * 排序字段
     */
    private Map<String, Object> sortFields;

    /**
     * 高亮字段
     */
    private List<String> hightLightFields;

    /**
     * 查询条件
     */
    private String queryCondition;

    /**
     * 查询字段
     */
    private List<String> queryFields;

    /**
     * 内容
     */
    private Map<String, Object> content;

    /**
     * 更新的内容
     */
    private Map<String, Object> newContents;

    /**
     * 分页号
     */
    private int pageNo;

    /**
     * 分页条数
     */
    private int size;
    /**
     * 必查的字段及值
     */
    private Map<String, Object> must;
    /**
     * 非必查的字段及值,与必查字段及值搭配使用,组成与或关系
     */
    private Map<String, Object> should;
    /**
     * 集群名称
     */
    private String clusterName;
    
    
    private List<Map<String,Object>> contents;
    
    /**
     * 一手房 suggest  区域type
     */
    private String areaType;
    
    /**
     * 一手房 suggest  stageNameType
     */
    private String stageNameType;
    
    /**
     * 一手房suggest   检索关键字
     */
    private String key;
    
    /**
     * 一手房suggest 城市代码 
     */
    private Integer cityCode;
    
    /**
     * 聚合字段
     */
    private String countField;
    
    /**
     * 求合字段
     */
    private String sumField ;

    /**
     * 先聚合再求和
     */
    private SumGroupbyModel sumGroupby;
    
    /**
     * 构造方法
     */
    public EsQueryModel() {
        super();
    }

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @return the index
     */
    public String getIndex() {
        return index;
    }

    /**
     * @return the type
     */
    public String getType() {
        return type;
    }

    /**
     * @return the queryConditions
     */
    public Map<String, Object> getQueryConditions() {
        return queryConditions;
    }

    /**
     * @return the rangeFields
     */
    public List<Map<String, Object>> getRangeFields() {
        return rangeFields;
    }

    /**
     * @return the sortFields
     */
    public Map<String, Object> getSortFields() {
        return sortFields;
    }

    /**
     * @return the hightLightFields
     */
    public List<String> getHightLightFields() {
        return hightLightFields;
    }

    /**
     * @return the queryCondition
     */
    public String getQueryCondition() {
        return queryCondition;
    }

    /**
     * @return the queryFields
     */
    public List<String> getQueryFields() {
        return queryFields;
    }

    /**
     * @return the content
     */
    public Map<String, Object> getContent() {
        return content;
    }

    /**
     * @return the newContents
     */
    public Map<String, Object> getNewContents() {
        return newContents;
    }

    /**
     * @return the pageNo
     */
    public int getPageNo() {
        return pageNo;
    }

    /**
     * @return the size
     */
    public int getSize() {
        return size;
    }

    /**
     * @return the must
     */
    public Map<String, Object> getMust() {
        return must;
    }

    /**
     * @return the should
     */
    public Map<String, Object> getShould() {
        return should;
    }

    /**
     * @param id
     *            the id to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setId(String id) {
        this.id = id;
        return this;
    }

    /**
     * @param index
     *            the index to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setIndex(String index) {
        this.index = index;
        return this;
    }

    /**
     * @param type
     *            the type to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setType(String type) {
        this.type = type;
        return this;
    }

    /**
     * @param queryConditions
     *            the queryConditions to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setQueryConditions(Map<String, Object> queryConditions) {
        this.queryConditions = queryConditions;
        return this;
    }

    /**
     * @param rangeFields
     *            the rangeFields to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setRangeFields(List<Map<String, Object>> rangeFields) {
        this.rangeFields = rangeFields;
        return this;
    }

    /**
     * @param sortFields
     *            the sortFields to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setSortFields(Map<String, Object> sortFields) {
        this.sortFields = sortFields;
        return this;
    }

    /**
     * @param hightLightFields
     *            the hightLightFields to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setHightLightFields(List<String> hightLightFields) {
        this.hightLightFields = hightLightFields;
        return this;
    }

    /**
     * @param queryCondition
     *            the queryCondition to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setQueryCondition(String queryCondition) {
        this.queryCondition = queryCondition;
        return this;
    }

    /**
     * @param queryFields
     *            the queryFields to set
     * @return EsQueryModel
     */
    public EsQueryModel setQueryFields(List<String> queryFields) {
        this.queryFields = queryFields;
        return this;
    }

    /**
     * @param content
     *            the content to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setContent(Map<String, Object> content) {
        this.content = content;
        return this;
    }

    /**
     * @param newContents
     *            the newContents to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setNewContents(Map<String, Object> newContents) {
        this.newContents = newContents;
        return this;
    }

    /**
     * @param pageNo
     *            the pageNo to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setPageNo(int pageNo) {
        this.pageNo = pageNo;
        return this;
    }

    /**
     * @param size
     *            the size to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setSize(int size) {
        this.size = size;
        return this;
    }

    /**
     * @param must
     *            the must to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setMust(Map<String, Object> must) {
        this.must = must;
        return this;
    }

    /**
     * @param should
     *            the should to set
     * 
     * @return EsQueryModel
     */

    public EsQueryModel setShould(Map<String, Object> should) {
        this.should = should;
        return this;
    }

    /**
     * @return the clusterName
     */
    public String getClusterName() {
        return clusterName;
    }

    /**
     * @param clusterName
     *            the clusterName to set
     * 
     * @return EsQueryModel
     */
    public EsQueryModel setClusterName(String clusterName) {
        this.clusterName = clusterName;
        return this;
    }

    /**
     * @return the contents
     */
    public List<Map<String, Object>> getContents() {
        return contents;
    }

    /**
     * @param contents the contents to set
     * @return EsQueryModel
     */
    public EsQueryModel setContents(List<Map<String, Object>> contents) {
        this.contents = contents;
        return this;
    }

    /**
     * 
     * @return
     * areaType
     */
    public String getAreaType() {
        return areaType;
    }

    /**
     * 
     * @param areaType
     * 设置一手房suggest  区域type
     *  
     *   @return EsQueryModel
     */
    public EsQueryModel setAreaType(String areaType) {
        this.areaType = areaType;
        return this;
    }

    /**
     * 
     * @return stageNameType
     */
    public String getStageNameType() {
        return stageNameType;
    }

    /**
     * 设置一手房suggest stageNameType
     * @param stageNameType stageNameType
     *  @return EsQueryModel
     */
    public EsQueryModel setStageNameType(String stageNameType) {
        this.stageNameType = stageNameType;
        return this;
    }

    /**
     * 
     * @return key
     */
    public String getKey() {
        return key;
    }

    /**
     * 设置一手房suggest 检索关键字
     * @param key  检索关键字
     *  @return EsQueryModel
     */
    public EsQueryModel setKey(String key) {
        this.key = key;
        return this;
    }

    /**
     * 城市代码 
     * @return 城市代码 
     */
    public Integer getCityCode() {
        return cityCode;
    }

    /**
     * 设置一手房suggest 城市代码
     * @param cityCode 城市代码 
     *  @return EsQueryModel
     */
    public EsQueryModel setCityCode(Integer cityCode) {
        this.cityCode = cityCode;
        return this;
    }

    /**
     * 获取聚合字段 名称
     * @return String
     */
    public String getCountField() {
        return countField;
    }

    /**
     * set 聚合字段名称
     * @param countField countField
     * @return EsQueryModel
     */
    public EsQueryModel setCountField(String countField) {
        this.countField = countField;
        return this; 
    }
    
    /**
     * 获取求和字段名称
     * @return String
     */
    public String getSumField() {
        return sumField;
    }

    /**
     * 设置求和字段名称
     * @param sumField sumField
     * @return EsQueryModel
     */
    public EsQueryModel  setSumField(String sumField) {
        this.sumField = sumField;
        return this;
    }

    public SumGroupbyModel getSumGroupby() {
        return sumGroupby;
    }

    public EsQueryModel setSumGroupby(SumGroupbyModel sumGroupby) {
        this.sumGroupby = sumGroupby;
        return this;
    }
    
    

}

action

/**
     * 往es中添加或者更新suggest索引信息 
     */
    private void insertEsSuggestInfo(NhStage po ){
        String result =null;
        
        
        
        List<CommonDictValue> keys = CommonDicUtils.getValues("cityCodeToCityDictKey");
    
        for(CommonDictValue cityToDic : keys){
            String citycode = cityToDic.getDictName();
            String cityname = CommonDicUtils.getDicName("city_code", citycode);
            String mappingType =   cityToDic.getDictValue();
            List<CommonDictValue> areas =    CommonDicUtils.getValues(mappingType);
            for(CommonDictValue area :areas){
                String districtName = area.getDictName();
                String districtCode = area.getDictValue();
                Long count = getCountOnshelfStageByCityAndArea(Integer.valueOf(citycode), Integer.valueOf(districtCode));
                String areaId = citycode+""+districtCode;
                Map<String,Object> areaContent = new HashMap<String,Object>();
                areaContent.put("num",count );
                areaContent.put("cityCode", citycode);
                areaContent.put("cityeName", cityname);
                areaContent.put("districtCode", districtCode);
                areaContent.put("districtName", districtName.toLowerCase());
                areaContent.put("spy", PinyinUtils.getFirstSpell(districtName).toLowerCase());
                areaContent.put("fpy", PinyinUtils.getFullSpell(districtName).toLowerCase() );
                result = ESClient.insert(ESContant.SUGGESTINDEX, ESContant.TYPEAREA, areaId, areaContent);
                if(logger.isInfoEnabled()){
                    logger.info("插入es suggest索引中的区域结果为"+result);
                }
                JSONObject resultObj = JSONObject.parseObject(result);
                boolean bSuccess = resultObj.getBooleanValue("success");
                if (!bSuccess)  {
                    logger.error("插入es suggest失败,返回结果不是true");
                    throw new RuntimeException("插入es suggest索引中的区域失败,返回结果不是true");
                }        
                
            }
        }
        
        
        
        //插入区域的suggest索引
        Integer cityCode = po.getCityCode();
        Integer districtCode = po.getDistrictCode();
        
        String cityDictKey = null;
        String districtName =null;
        
        for(CommonDictValue dicValue :keys){
            if(dicValue.getDictName().equals(cityCode.toString())){
                cityDictKey = dicValue.getDictValue();
            }
        }
        if(StringUtils.isNotBlank(cityDictKey)){
            districtName = CommonDicUtils.getDicName(cityDictKey, String.valueOf(districtCode));
        }
        
         
        
        //插入楼盘的suggest索引信息
        Map<String,Object> stageContent = new HashMap<String,Object>();
        stageContent.put("cityCode", cityCode);
        stageContent.put("cityeName", CommonDicUtils.getDicName("city_code", cityCode+""));
        stageContent.put("districtCode", districtCode);
        stageContent.put("districtName", districtName);
        stageContent.put("stageName", po.getStageName());
        stageContent.put("stageAlias1", po.getStageAlias1());
        stageContent.put("stageAlias2", po.getStageAlias2());
        stageContent.put("stageAlias3", po.getStageAlias3());
        stageContent.put("propertyName",CommonDicUtils.getDicName("property_type", po.getPropertyType()+""));
        stageContent.put("propertyType", po.getPropertyType());
        stageContent.put("sortNum", po.getSortNum());
        //地区首拼音
        stageContent.put("districtNameSPY", PinyinUtils.getFirstSpell(districtName).toLowerCase());
        //地区全拼
        stageContent.put("districtNameFPY",PinyinUtils.getFullSpell(districtName).toLowerCase());
        
        
        StringBuffer stageNames = new StringBuffer(po.getStageName());
        if(StringUtils.isNotBlank(po.getStageAlias1())){
            stageNames.append(po.getStageAlias1());
        }
        if(StringUtils.isNotBlank(po.getStageAlias2())){
            stageNames.append(po.getStageAlias2());
        }
        if(StringUtils.isNotBlank(po.getStageAlias3())){
            stageNames.append(po.getStageAlias3());
        }
        stageContent.put("stageNames", stageNames.toString().toLowerCase());
        stageContent.put("fpy", PinyinUtils.getFullSpell(stageContent.get("stageNames").toString()).toLowerCase() );
        stageContent.put("spy", PinyinUtils.getFirstSpell(stageContent.get("stageNames").toString()).toLowerCase() );
        
        result = ESClient.insert(ESContant.SUGGESTINDEX, ESContant.TYPESTAGENAME, po.getId(), stageContent);
        if(logger.isInfoEnabled()){
            logger.info("插入es suggest索引中楼盘的结果为"+result);
        }
        JSONObject resultObj = JSONObject.parseObject(result);
        boolean bSuccess = resultObj.getBooleanValue("success");
        if (!bSuccess)  {
            logger.error("插入es suggest索引中楼盘失败,返回结果不是true");
            throw new RuntimeException("插入插入es suggest索引中楼盘失败,返回结果不是true");
        }    
    }
    

 

posted @ 2018-08-04 16:20  十月围城小童鞋  阅读(359)  评论(0编辑  收藏  举报