怎么把达梦数据库文件sql文件导入es中

我是把达梦数据库文件导出到sql文件中
然后再解析sql文件中分批导入到es中

package com.jinw.es;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.google.common.collect.Lists;
import com.jinw.activity.service.IProcessFormService;
import com.jinw.base.model.PageInfo;
import com.jinw.base.model.ProcessForm;
import com.jinw.base.model.QueryVo;
import com.jinw.base.model.RestResult;
import com.jinw.modules.applyCar.domain.ApplyCarParameterVo;
import com.jinw.modules.business.service.IFlowCommonService;
import com.jinw.modules.car.domain.UserCarVo;
import com.jinw.modules.card.domain.UserCardVo;
import com.jinw.modules.excelLogs.domain.IssueVo;
import com.jinw.utils.StringUtils;
import com.jinw.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhrasePrefixQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.context.annotation.Lazy;
import com.jinw.base.controller.BaseCommonController;
import com.jinw.modules.excelLogs.domain.BTExcelLogs;
import com.jinw.modules.excelLogs.service.IBTExcelLogsService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liuxin
 * @Description:
 * @date 2024-04-08
 */

@RestController
@RequestMapping("/es")
@Api(tags = "es")
@Slf4j
public class EsController {

    @Autowired
    private EsDataOperation esDataOperation;
    @Autowired
    private EsIndexOperation esIndexOperation;
    @Autowired
    private EsQueryOperation esQueryOperation;

    @PostMapping("createIndex")
    public void createIndex(String indexName, String filePath) {
  
        boolean b = esIndexOperation.createIndex(indexName, filePath);
        Assert.isTrue(b);
    }

    @PostMapping("insert")
    public void insert(String indexName, String filePath) throws IOException {
      
        parseSqlFile(filePath, indexName);
    }

    public void parseSqlFile(String filePath, String indexName) {
        int batchSize = 100000; // 设置批次大小
        List<Map<String, Object>> dataList = null;
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            int totalLines = FileUtil.getTotalLines(FileUtil.file(filePath)); // 获取总行数
            System.out.println("Total lines in SQL file: " + totalLines);
            int batchCount = (int) Math.ceil((double) totalLines / batchSize); // 计算批次数量
            System.out.println("Total batches to execute: " + batchCount);
            // 循环读取数据
            for (int batchIndex = 0; batchIndex < batchCount; batchIndex++) {
                int linesRead = 0;
                dataList = Lists.newArrayList();
                System.out.println("Batch " + (batchIndex + 1) + "/" + batchCount + ":");

                // 读取每个批次的数据
                String line;
                while ((line = reader.readLine()) != null && linesRead < batchSize) {
                    if (!line.trim().isEmpty()) { // 判断是否为空行
                        linesRead++;
                        // 在这里处理每一行的数据,例如执行 SQL 操作等
                        // System.out.println("line:" + line);
                        Map<String, Object> map = parseInsertStatement(line);
                        dataList.add(map);
                    }
                }
                if (ObjectUtil.isNotEmpty(dataList)) {
                    boolean flag = esDataOperation.batchInsert(indexName, dataList);
                    System.out.println("flag:" + flag);
                }
                System.out.println("Batch " + (batchIndex + 1) + " processed. Lines read: " + linesRead);
            }
            System.out.println("Total lines read: " + totalLines);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, Object> parseInsertStatement(String line) {
        line = line.replaceAll("INSERT INTO \"xxx\".\"xx_INOUT_LOGS\"\\(", "")
                .replaceAll("\\)", "").replaceAll(";", "");
        line = line.replaceAll("INSERT INTO \"xxx\".\"xx_GETOUT_LOGS\"\\(", "")
                .replaceAll("\\)", "").replaceAll(";", "");
        String[] values = line.split("VALUES\\(");
        Map<String, Object> dataMap = new HashMap<>();
        String[] split = values[0].split(",");
        String[] split1 = values[1].split(",");
        for (int i = 0; i < split.length; i++) {
            String stringWithoutQuotes = StrUtil.toCamelCase(split[i].toLowerCase().replaceAll("\"", ""));
            String stringWithoutQuotes2 = split1[i].replaceAll("\"", "").replaceAll("'", "");
            dataMap.put(stringWithoutQuotes, stringWithoutQuotes2);
        }
        return dataMap;
    }

    @PostMapping("update")
    public void update() {
        String indexName = "b_t_people_inout_logs";
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", 5);
        hashMap.put("name", "jack7");
        boolean update = esDataOperation.update(indexName, hashMap, WriteRequest.RefreshPolicy.WAIT_UNTIL);
        Assert.isTrue(update);
    }

    /**
     * 查询总数
     */
    @GetMapping("count")
    public Long count(String indexName) {
        return esQueryOperation.count(indexName);
    }

    @GetMapping("list")
    public List<Map<String, Object>> list(String indexName) {
        // 查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //精确查询
        //  BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        //  queryBuilder.must(QueryBuilders.termQuery("personName", "xxx"));

        //模糊查询
        //  MatchPhrasePrefixQueryBuilder matchQueryBuilder = QueryBuilders.matchPhrasePrefixQuery("personName", "杨");


        // 设置模糊查询
        //  sourceBuilder.query(QueryBuilders.fuzzyQuery("personName", "马中明"));

        // 设置排序规则
        //sourceBuilder.sort(SortBuilders.fieldSort("eventTime").order(SortOrder.DESC));
        // 设置超时时间
        sourceBuilder.timeout(TimeValue.timeValueSeconds(10));

        // 分页查询
        sourceBuilder.from(0);
        sourceBuilder.size(10);
        List<Map<String, Object>> list = esQueryOperation.list(indexName, sourceBuilder);
        return list;
    }
}

另外如果要排序的话要把字段类型 设置为keyword
字段映射配置:

{
    "aliases": {
        "btcgl": {}
    },
    "mappings": {
        "properties": {
            "userId": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "quartersId": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "carName": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "quartersName": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "crossTime": {
                "type": "keyword",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "plateNo": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "crossRecordSyscode": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "parkSyscode": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "parkName": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "entranceSyscode": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "entranceName": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "roadwaySyscode": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "roadwayName": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "vehicleOut": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "cardNo": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "releaseMode": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "releaseResult": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "releaseWay": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "releaseReason": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "vehicleColor": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "vehicleType": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "plateColor": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "plateType": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "carCategory": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "carCategoryName": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            },
            "orgId": {
                "type": "text",
                "fields": {
                    "keyword": {
                        "type": "keyword",
                        "ignore_above": 256
                    }
                }
            }
        }
    },
    "settings": {
        "index": {
            "number_of_shards": "1",
            "number_of_replicas": "1"
        }
    }
}
package com.jinw.modules.utils;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.jinw.es.EsDataOperation;
import com.jinw.es.EsQueryOperation;
import com.jinw.utils.spring.SpringUtils;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @author @liuxin
 * @classname ESUtils
 * @date 2024/4/9 8:40
 * @description TODO
 */
@Component
public class ESUtils {
    private static EsQueryOperation esQueryOperation = SpringUtils.getBean(EsQueryOperation.class);
    private static EsDataOperation esDataOperation = SpringUtils.getBean(EsDataOperation.class);

    public static List<Map<String, Object>> selectByPage(String indexName, SearchSourceBuilder sourceBuilder, int pageNum, int pageSize) {
        // 设置超时时间
        sourceBuilder.timeout(TimeValue.timeValueSeconds(10));
        // 分页查询
        sourceBuilder.from((pageNum - 1) * pageSize);
        sourceBuilder.size(pageSize);
        sourceBuilder.trackTotalHits(true);
        List<Map<String, Object>> result = esQueryOperation.list(indexName, sourceBuilder);
        return ObjectUtil.isNotEmpty(result) ? result : Lists.newArrayList();
    }

    public static Long selectByCount(String indexName, SearchSourceBuilder sourceBuilder) {
        return esQueryOperation.countByCondition(indexName, sourceBuilder);
    }


    public static Map<String, Object> selectOneById(
            String indexName, String recordId) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("id", recordId);
        // 添加到布尔查询的 should 子句中
        sourceBuilder.query(termQueryBuilder);
        List<Map<String, Object>> list = esQueryOperation.list(indexName, sourceBuilder);
        Map<String, Object> entity = null;
        if (ObjectUtil.isNotEmpty(list)) {
            entity = list.get(0);
        }
        return entity;
    }

    public static boolean deleteById(
            String indexName, String recordId) {
        return esDataOperation.delete(indexName, recordId);
    }


    public static boolean insert(String indexName, Map<String, Object> dataMap) {
        return esDataOperation.insert(indexName, dataMap);
    }
}
package com.jinw.es.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * restHighLevelClient 客户端配置类
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchConfig {

    /**
     * es host ip 地址(集群)
     */
    private String hosts;
    /**
     * es用户名
     */
    private String userName;
    /**
     * es密码
     */
    private String password;
    /**
     * es 请求方式
     */
    private String scheme;
    /**
     * es 连接超时时间
     */
    private int connectTimeOut;
    /**
     * es socket 连接超时时间
     */
    private int socketTimeOut;
    /**
     * es 请求超时时间
     */
    private int connectionRequestTimeOut;
    /**
     * es 最大连接数
     */
    private int maxConnectNum;
    /**
     * es 每个路由的最大连接数
     */
    private int maxConnectNumPerRoute;


    /**
     * 如果@Bean没有指定bean的名称,那么方法名就是bean的名称
     */
    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient restHighLevelClient() {
        // 构建连接对象
        RestClientBuilder builder = RestClient.builder(getEsHost());

        // 连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(connectTimeOut);
            requestConfigBuilder.setSocketTimeout(socketTimeOut);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
            return requestConfigBuilder;
        });

        // 连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(maxConnectNum);
            httpClientBuilder.setMaxConnPerRoute(maxConnectNumPerRoute);
            httpClientBuilder.setDefaultCredentialsProvider(getCredentialsProvider());
            return httpClientBuilder;
        });

        return new RestHighLevelClient(builder);
    }

    private HttpHost[] getEsHost() {
        // 拆分地址(es为多节点时,不同host以逗号间隔)
        List<HttpHost> hostLists = new ArrayList<>();
        String[] hostList = hosts.split(",");
        for (String addr : hostList) {
            String host = addr.split(":")[0];
            String port = addr.split(":")[1];
            hostLists.add(new HttpHost(host, Integer.parseInt(port), scheme));
        }
        // 转换成 HttpHost 数组
        return hostLists.toArray(new HttpHost[]{});
    }

    private CredentialsProvider getCredentialsProvider() {
        // 设置用户名、密码
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        return credentialsProvider;
    }
}
package com.jinw.es;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 增删改数据
 */
@Slf4j
@Service
public class EsDataOperation {

    @Resource
    private RestHighLevelClient client;
    private final RequestOptions options = RequestOptions.DEFAULT;

    /**
     * 写入数据
     */
    public boolean insert(String indexName, Map<String, Object> dataMap) {
        try {
            BulkRequest request = new BulkRequest();
            request.add(new IndexRequest(indexName).opType("create")
                    .id(dataMap.get("id").toString())
                    .source(dataMap, XContentType.JSON));
            this.client.bulk(request, options);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("EsDataOperation insert error.", e);
        }
        return Boolean.FALSE;
    }

    /**
     * 批量写入数据
     */
    public boolean batchInsert(String indexName, List<Map<String, Object>> userIndexList) {
        try {
            BulkRequest request = new BulkRequest();
            for (Map<String, Object> dataMap : userIndexList) {
                request.add(new IndexRequest(indexName).opType("create")
                        .id(dataMap.get("id").toString())
                        .source(dataMap, XContentType.JSON));
            }
            this.client.bulk(request, options);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("EsDataOperation batchInsert error.", e);
        }
        return Boolean.FALSE;
    }

    /**
     * 根据id更新数据,可以直接修改索引结构
     *
     * @param refreshPolicy 数据刷新策略
     */
    public boolean update(String indexName, Map<String, Object> dataMap, WriteRequest.RefreshPolicy refreshPolicy) {
        try {
            UpdateRequest updateRequest = new UpdateRequest(indexName, dataMap.get("id").toString());
            updateRequest.setRefreshPolicy(refreshPolicy);
            updateRequest.doc(dataMap);
            this.client.update(updateRequest, options);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("EsDataOperation update error.", e);
        }
        return Boolean.FALSE;
    }

    /**
     * 删除数据
     */
    public boolean delete(String indexName, String id) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest(indexName, id);
            this.client.delete(deleteRequest, options);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("EsDataOperation delete error.", e);
        }
        return Boolean.FALSE;
    }


    /**
     * 批量删除数据
     */
    public boolean batchDelete(String indexName, String fieldName, String fieldValue) {
        try {
            // 设置滚动参数
            Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1L));

            // 构建初始查询请求
            SearchRequest searchRequest = new SearchRequest(indexName);
            searchRequest.scroll(scroll);

            // 构建查询条件
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.rangeQuery(fieldName).lt(fieldValue));
            searchRequest.source(sourceBuilder);

            // 执行初始查询请求
            SearchResponse searchResponse = client.search(searchRequest, options);

            // 获取滚动ID
            String scrollId = searchResponse.getScrollId();

            // 构建批量删除请求
            BulkRequest bulkRequest = new BulkRequest();

            // 循环获取滚动结果并添加到批量删除请求中
            while (true) {
                for (SearchHit hit : searchResponse.getHits().getHits()) {
                    bulkRequest.add(new DeleteRequest(indexName, hit.getId()));
                }

                // 执行批量删除请求
                BulkResponse bulkResponse = client.bulk(bulkRequest, options);

                // 检查是否还有滚动结果
                if (bulkResponse.getItems().length == 0) {
                    break;
                }

                // 继续滚动搜索
                SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
                scrollRequest.scroll(scroll);
                searchResponse = client.scroll(scrollRequest, options);
            }

            // 清除滚动ID
            ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
            clearScrollRequest.addScrollId(scrollId);
            client.clearScroll(clearScrollRequest, options);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("EsDataOperation delete error.", e);
        }
        return Boolean.FALSE;
    }
}
package com.jinw.es;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 操作ES索引
 */
@Slf4j
@Service
public class EsIndexOperation {

    @Resource
    private RestHighLevelClient restHighLevelClient;
    private final RequestOptions options = RequestOptions.DEFAULT;

    /**
     * 判断索引是否存在
     */
    public boolean checkIndex(String index) {
        try {
            return restHighLevelClient.indices().exists(new GetIndexRequest(index), options);
        } catch (Exception e) {
            log.error("EsIndexOperation checkIndex error.", e);
        }
        return Boolean.FALSE;
    }

    /**
     * 创建索引
     *
     * @param indexName         es索引名
     * @param esSettingFilePath es索引的alias、settings和mapping的配置文件
     */
    public boolean createIndex(String indexName, String esSettingFilePath) {
        String aliases = null;
        String mappings = null;
        String settings = null;
        if (StringUtils.isNotBlank(esSettingFilePath)) {
            try {
                String fileContent = FileUtil.readUtf8String(esSettingFilePath);
                if (StringUtils.isNotBlank(fileContent)) {
                    JSONObject jsonObject = JSON.parseObject(fileContent);
                    aliases = jsonObject.getString("aliases");
                    mappings = jsonObject.getString("mappings");
                    settings = jsonObject.getString("settings");
                }
            } catch (Exception e) {
                log.error("createIndex error.", e);
                return false;
            }
        }

        if (checkIndex(indexName)) {
            log.error("createIndex indexName:[{}]已存在", indexName);
            return false;
        }

        CreateIndexRequest request = new CreateIndexRequest(indexName);
        if ((StringUtils.isNotBlank(aliases))) {
            request.aliases(aliases, XContentType.JSON);
        }

        if (StringUtils.isNotBlank(mappings)) {
            request.mapping(mappings, XContentType.JSON);
        }

        if (StringUtils.isNotBlank(settings)) {
            request.settings(settings, XContentType.JSON);
        }

        try {
            this.restHighLevelClient.indices().create(request, options);
            return true;
        } catch (IOException e) {
            log.error("EsIndexOperation createIndex error.", e);
            return false;
        }
    }

    /**
     * 删除索引
     */
    public boolean deleteIndex(String indexName) {
        try {
            if (checkIndex(indexName)) {
                DeleteIndexRequest request = new DeleteIndexRequest(indexName);
                AcknowledgedResponse response = restHighLevelClient.indices().delete(request, options);
                return response.isAcknowledged();
            }
        } catch (Exception e) {
            log.error("EsIndexOperation deleteIndex error.", e);
        }
        return Boolean.FALSE;
    }
}
package com.jinw.es;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 查询操作
 */
@Slf4j
@Service
public class EsQueryOperation {

    @Resource
    private RestHighLevelClient client;
    private final RequestOptions options = RequestOptions.DEFAULT;

    /**
     * 查询总数
     */
    public Long count(String indexName) {
        CountRequest countRequest = new CountRequest(indexName);
        try {
            CountResponse countResponse = client.count(countRequest, options);
            return countResponse.getCount();
        } catch (Exception e) {
            log.error("EsQueryOperation count error.", e);
        }
        return 0L;
    }


    /**
     * 查询总数
     */
    public Long countByCondition(String indexName, SearchSourceBuilder sourceBuilder) {
        CountRequest countRequest = new CountRequest(indexName);
        countRequest.source(sourceBuilder);
        try {
            CountResponse countResponse = client.count(countRequest, options);
            return countResponse.getCount();
        } catch (Exception e) {
            log.error("EsQueryOperation count error.", e);
        }
        return 0L;
    }

    /**
     * 查询数据集
     */
    public List<Map<String, Object>> list(String indexName, SearchSourceBuilder sourceBuilder) {
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(sourceBuilder);
        try {
            SearchResponse searchResp = client.search(searchRequest, options);
            List<Map<String, Object>> data = new ArrayList<>();
            SearchHit[] searchHitArr = searchResp.getHits().getHits();
            for (SearchHit searchHit : searchHitArr) {
                Map<String, Object> temp = searchHit.getSourceAsMap();
                temp.put("id", searchHit.getId());
                data.add(temp);
            }
            return data;
        } catch (Exception e) {
            log.error("EsQueryOperation list error.", e);
        }
        return null;
    }


}

如何优化mysql语句

转自:https://www.cnblogs.com/lonnie/p/8320095.html
1.对查询进行优化,在涉及到where或order by的列上建立索引
2.应避免在where子句上使用不等号或者大于小于符号,可能会导致放弃索引查询而全表查询
3.在where后不用做非null查询,会导致放弃索引查询而做全表查询

1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。

2.应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放弃使用索引而进行全表扫描。

3.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:
select id from t where num is null
可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:
select id from t where num=0

4.应尽量避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,如:
select id from t where num=10 or num=20
可以这样查询:
select id from t where num=10
union all
select id from t where num=20

5.下面的查询也将导致全表扫描:
select id from t where name like '%abc%'
若要提高效率,可以考虑全文检索。

6.in 和 not in 也要慎用,否则会导致全表扫描,如:
select id from t where num in(1,2,3)
对于连续的数值,能用 between 就不要用 in 了:
select id from t where num between 1 and 3

7.如果在 where 子句中使用参数,也会导致全表扫描。因为SQL只有在运行时才会解析局部变量,但优化程序不能将访问计划的选择推迟到运行时;它必须在编译时进行选择。然而,如果在编译时建立访问计划,变量的值还是未知的,因而无法作为索引选择的输入项。如下面语句将进行全表扫描:
select id from t where num=@num
可以改为强制查询使用索引:
select id from t with(index(索引名)) where num=@num

8.应尽量避免在 where 子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描。如:
select id from t where num/2=100
应改为:
select id from t where num=100*2

9.应尽量避免在where子句中对字段进行函数操作,这将导致引擎放弃使用索引而进行全表扫描。如:
select id from t where substring(name,1,3)='abc'--name以abc开头的id
select id from t where datediff(day,createdate,'2005-11-30')=0--'2005-11-30'生成的id
应改为:
select id from t where name like 'abc%'
select id from t where createdate>='2005-11-30' and createdate<'2005-12-1'

10.不要在 where 子句中的“=”左边进行函数、算术运算或其他表达式运算,否则系统将可能无法正确使用索引。

11.在使用索引字段作为条件时,如果该索引是复合索引,那么必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引,否则该索引将不会被使用,并且应尽可能的让字段顺序与索引顺序相一致。

12.不要写一些没有意义的查询,如需要生成一个空表结构:
select col1,col2 into #t from t where 1=0
这类代码不会返回任何结果集,但是会消耗系统资源的,应改成这样:
create table #t(...)

13.很多时候用 exists 代替 in 是一个好的选择:
select num from a where num in(select num from b)
用下面的语句替换:
select num from a where exists(select 1 from b where num=a.num)

14.并不是所有索引对查询都有效,SQL是根据表中数据来进行查询优化的,当索引列有大量数据重复时,SQL查询可能不会去利用索引,如一表中有字段sex,male、female几乎各一半,那么即使在sex上建了索引也对查询效率起不了作用。

15.索引并不是越多越好,索引固然可以提高相应的 select 的效率,但同时也降低了 insert 及 update 的效率,因为 insert 或 update 时有可能会重建索引,所以怎样建索引需要慎重考虑,视具体情况而定。一个表的索引数最好不要超过6个,若太多则应考虑一些不常使用到的列上建的索引是否有必要。

16.应尽可能的避免更新 clustered 索引数据列,因为 clustered 索引数据列的顺序就是表记录的物理存储顺序,一旦该列值改变将导致整个表记录的顺序的调整,会耗费相当大的资源。若应用系统需要频繁更新 clustered 索引数据列,那么需要考虑是否应将该索引建为 clustered 索引。

17.尽量使用数字型字段,若只含数值信息的字段尽量不要设计为字符型,这会降低查询和连接的性能,并会增加存储开销。这是因为引擎在处理查询和连接时会逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了。

18.尽可能的使用 varchar/nvarchar 代替 char/nchar ,因为首先变长字段存储空间小,可以节省存储空间,其次对于查询来说,在一个相对较小的字段内搜索效率显然要高些。

19.任何地方都不要使用 select from t ,用具体的字段列表代替“”,不要返回用不到的任何字段。

20.尽量使用表变量来代替临时表。如果表变量包含大量数据,请注意索引非常有限(只有主键索引)。

21.避免频繁创建和删除临时表,以减少系统表资源的消耗。

22.临时表并不是不可使用,适当地使用它们可以使某些例程更有效,例如,当需要重复引用大型表或常用表中的某个数据集时。但是,对于一次性事件,最好使用导出表。

23.在新建临时表时,如果一次性插入数据量很大,那么可以使用 select into 代替 create table,避免造成大量 log ,以提高速度;如果数据量不大,为了缓和系统表的资源,应先create table,然后insert。

24.如果使用到了临时表,在存储过程的最后务必将所有的临时表显式删除,先 truncate table ,然后 drop table ,这样可以避免系统表的较长时间锁定。

25.尽量避免使用游标,因为游标的效率较差,如果游标操作的数据超过1万行,那么就应该考虑改写。

26.使用基于游标的方法或临时表方法之前,应先寻找基于集的解决方案来解决问题,基于集的方法通常更有效。

27.与临时表一样,游标并不是不可使用。对小型数据集使用 FAST_FORWARD 游标通常要优于其他逐行处理方法,尤其是在必须引用几个表才能获得所需的数据时。在结果集中包括“合计”的例程通常要比使用游标执行的速度快。如果开发时间允许,基于游标的方法和基于集的方法都可以尝试一下,看哪一种方法的效果更好。

28.在所有的存储过程和触发器的开始处设置 SET NOCOUNT ON ,在结束时设置 SET NOCOUNT OFF 。无需在执行存储过程和触发器的每个语句后向客户端发送 DONE_IN_PROC 消息。

29.尽量避免向客户端返回大数据量,若数据量过大,应该考虑相应需求是否合理。

30.尽量避免大事务操作,提高系统并发能力。