EsTool.java 9.25 KB
package com.lhcredit.common.utils.elasticSearchUtils;

import com.alibaba.fastjson.JSONObject;
import com.lhcredit.common.utils.elasticSearchUtils.config.EsConfig;
import com.lhcredit.project.system.dict.domain.DictData;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;

@Component
public class EsTool {
    /**ik分词字段 */
    private String[] ikField;
    public EsTool ikField(String... FieldName){
        this.ikField=FieldName;
        return this;
    }
    /**开启fieldData的字段 */
    private String[] fieldData;
    public EsTool fieldData(String... fieldData){
        this.fieldData=fieldData;
        return this;
    }
    private Long scrollTime=30000L ;//设置scroll保存时间 分钟单位
    private Integer number_of_shards=1;//设置分片
    private Integer number_of_replicas=1;//设置副本
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private EsConfig esConfig;

    public static Logger log= LoggerFactory.getLogger(EsTool.class);

    /**根据实体类创建索引  index和type相同 */
    public Boolean createIdx(Class cs,String idx,String typeName) throws IOException {
        //获取字段
        Field[] fields = cs.getDeclaredFields();
        //验证索引
//        if(isExistsIndex(cs.getSimpleName().toLowerCase())){
//            return false;
//        }
        log.info("index={}", cs.getSimpleName().toLowerCase());
        //索引和type同名,全部小写
//        CreateIndexRequest request = new CreateIndexRequest("lhtlzsh");
        CreateIndexRequest request = new CreateIndexRequest(idx);
        XContentBuilder builder = JsonXContent.contentBuilder();
        builder.startObject()
                .startObject("mappings")
//                .startObject("lhtlzsh")
                .startObject(typeName)
                .startObject("properties");
        for(Field field : fields){
            Class<?> type = field.getType();
            //这里只对String类型的字段添加ik中文分词处理
            if(type.getSimpleName().equals("String")) {
                if (Arrays.asList(ikField).contains(field.getName())) {
                    //分词
                    builder.startObject(field.getName())
                            .field("type", "text")
                            .field("index", true)
                            .field("analyzer", "ik_max_word")
//                            .field("analyzer","standard")
                            .endObject();
                }else {
                    //不分词
                    builder.startObject(field.getName())
                            .field("type", "text")
                            .field("index", true)
                            .endObject();
                }
            }
            //对数字处理
            if(type.getSimpleName().equals("Integer")||type.getSimpleName().equals("int")){
                builder.startObject(field.getName())
                        .field("type","integer")
                        .field("index",true)
                        .endObject();

            }
            if(type.getSimpleName().equals("Long")||type.getSimpleName().equals("long")){
                builder.startObject(field.getName())
                        .field("type","long")
                        .field("index",true)
                        .endObject();
            }
            if(type.getSimpleName().equals("Float")||type.getSimpleName().equals("float")){
                builder.startObject(field.getName())
                        .field("type","float")
                        .field("index",true)
                        .endObject();

            }
            if(type.getSimpleName().equals("Double")||type.getSimpleName().equals("double")||type.getSimpleName().equals("BigDecimal")){
                builder.startObject(field.getName())
                        .field("type","double")
                        .field("index",true)
                        .endObject();
            }
            //日期
            if(type.getSimpleName().equals("Date")){
                builder.startObject(field.getName())
                        .field("type","date")
                        .field("index",true)
                        .endObject();
            }
            //boolean
            if(type.getSimpleName().equals("Boolean")||type.getSimpleName().equals("boolean")){
                builder.startObject(field.getName())
                        .field("type","boolean")
                        .field("index",true)
                        .endObject();
            }
        }
        builder.endObject().endObject().endObject();
        builder.startObject("settings")
                //分片数
                .field("number_of_shards",number_of_shards)
                //副本数,1台机器设为0
                .field("number_of_replicas",number_of_replicas)
                .endObject()
                .endObject();

        request.source(builder);
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        log.info(JSONObject.toJSONString(response));
        return response.isAcknowledged();
    }
    /** 删除索引 */
    public boolean deleteIndex(String index){
        if(!isExistsIndex(index)){
            return false;
        };
        DeleteIndexRequest request=new DeleteIndexRequest(index);
        try {
            AcknowledgedResponse deleteIndexResponse = client.indices().delete(request,RequestOptions.DEFAULT);
            return deleteIndexResponse.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**验证索引是否存在 */
    public boolean isExistsIndex(String indexName){
        try{
            GetIndexRequest request = new GetIndexRequest();
            request.indices(indexName);
            boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
            return exists;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    //设置fieldData
    public void setFieldData(String idx,String... field){
        for(int i=0;i<field.length;i++){
            String url="http://"+esConfig.getHost()+":"+esConfig.getPort()+"/"+idx+"/"+idx+"/_mapping";
            String data="{\"properties\":{\""+field[i]+"\":{\"type\": \"text\",\"fielddata\": true}}}";
            String request=doPut(url,data);
            System.out.println("开启"+field[i]+":"+request);
        }

    }
    //put请求
    public  String doPut(String url, String jsonStr) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        httpPut.setHeader("Content-type", "application/json");
        httpPut.setHeader("DataEncoding", "UTF-8");
//        httpPut.setHeader("token", token);

        CloseableHttpResponse httpResponse = null;
        try {
            httpPut.setEntity(new StringEntity(jsonStr));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}