一、RestHighLevelClient 配置

package cn.hsa.csc.query.config;

import cn.hsa.hsaf.core.framework.web.exception.BusinessException;
import cn.hsa.utils.elasticsearch.Assert;
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.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
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 org.elasticsearch.common.xcontent.DeprecationHandler;

import java.util.Arrays;
import java.util.Objects;

/**
 * es 初始化配置
 *
 * @author lsj
 * @date 2021/11/3 14:35
 */
@Configuration
@ConfigurationProperties(prefix = "es")
@Slf4j
@Data
public class ElasticsearchConfig {
    private String hosts;
    private String username;
    private String password;
    private int connectTimeout;
    private int socketTimeout;
    private int connectionRequestTimeout;

    @Bean
    public RestHighLevelClient client() {
        log.info("elasticsearch init start ");
        Assert.hasLength(hosts, "elasticsearch host is null");
        HttpHost[] httpHosts = Arrays.stream(hosts.split(",")).map(host -> {
            Assert.hasLength(host, "elasticsearch host is null");
            String[] h = host.split(":");
            if (h.length != 2) throw new BusinessException("host ip or port formate is error");
            return new HttpHost(h[0], Integer.parseInt(h[1]));
        }).filter(Objects::nonNull).toArray(HttpHost[]::new);
        RestClientBuilder builder = RestClient.builder(httpHosts);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider))
                .setRequestConfigCallback(r -> {
                    r.setConnectTimeout(connectTimeout);
                    r.setSocketTimeout(socketTimeout);
                    r.setConnectionRequestTimeout(connectionRequestTimeout);
                    return r;
                });
        return new RestHighLevelClient(builder);
    }
}

配置

es:
  hosts: 127.0.0.1:19200,127.0.0.1:19201,127.0.0.1:19202
  username: elastic
  password: ylz@123
  connectTimeout: 30000
  socketTimeout: 30000
  connectionRequestTimeout: 30000

二、对应工具类

package cn.hsa.utils.elasticsearch;

import cn.hsa.hsaf.core.framework.web.exception.BusinessException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.index.reindex.UpdateByQueryRequest;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * es工具类型
 *
 * @author lsj
 * @date 2021/11/3 15:17
 */
@Component
@Slf4j
public class ElasticsearchUtils {
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    /**
     * 添加索引
     *
     * @param indexName
     * @return
     * @throws IOException
     */
    public boolean addIndex(String indexName) {
        Assert.hasLength(indexName, "Elasticsearch exception indexName null");
        CreateIndexResponse createIndexResponse = null;
        try {
            //1.使用client获取操作索引对象
            IndicesClient indices = restHighLevelClient.indices();
            //2.具体操作获取返回值
            //2.1 设置索引名称
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
            createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("elasticsearch addindex error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch addindex error , meassage=" + e.getMessage());
        }

        //3.根据返回值判断结果
        return createIndexResponse.isAcknowledged();
    }

    /**
     * 删除索引
     *
     * @param indexName
     * @return
     * @throws IOException
     */
    public boolean deleteIndex(String indexName) {
        Assert.hasLength(indexName, "Elasticsearch exception indexName null");
        AcknowledgedResponse deleteRespone = null;
        try {
            //1.使用client获取操作索引对象
            IndicesClient indices = restHighLevelClient.indices();
            //2.具体操作获取返回值
            //2.1 设置索引名称
            DeleteIndexRequest request = new DeleteIndexRequest("twitter_two");//指定要删除的索引名称
            deleteRespone = indices.delete(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("elasticsearch deleteIndex error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch deleteIndex error , meassage=" + e.getMessage());
        }
        //3.根据返回值判断结果
        return deleteRespone.isAcknowledged();
    }

    /**
     * 创建数据
     *
     * @param indexName
     * @param id
     * @param data
     * @throws IOException
     */
    public boolean addData(String indexName, String id, Object data) {
        Assert.notNull(data, "Elasticsearch exception data null");
        Assert.hasLength(indexName, "Elasticsearch exception indexName null");
        IndexResponse indexResponse = null;
        try {
            //准备文档
            String jsonString = JSONObject.toJSONString(data);
            Map jsonMap = JSONObject.parseObject(jsonString, Map.class);
            //创建请求
            IndexRequest indexRequest = new IndexRequest(indexName).id(id);
            //指定文档内容
            indexRequest.source(jsonMap);
            //true 当存在相同的_id时,插入会出现异常; false 当存在相同_id时,插入会进行覆盖;
            indexRequest.create(true);
            //通过client进行http请求
            indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("elasticsearch addOrUpdateDoc error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch addOrUpdateDoc error , meassage=" + e.getMessage());
        }
        return indexResponse.getResult().equals(DocWriteResponse.Result.CREATED);
    }

    /**
     * 创建文档id存在则更新文档
     *
     * @param indexName
     * @param id
     * @param data
     * @throws IOException
     */
    public boolean addOrUpdateData(String indexName, String id, Object data) {
        Assert.notNull(data, "Elasticsearch exception data null");
        Assert.hasLength(indexName, "Elasticsearch exception indexName null");
        IndexResponse indexResponse = null;
        try {
            //准备文档
            String jsonString = JSONObject.toJSONString(data);
            Map jsonMap = JSONObject.parseObject(jsonString, Map.class);
            //创建请求
            IndexRequest indexRequest = new IndexRequest(indexName).id(id);
            //指定文档内容
            indexRequest.source(jsonMap);
            //通过client进行http请求
            indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("elasticsearch addOrUpdateDoc error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch addOrUpdateDoc error , meassage=" + e.getMessage());
        }
        return indexResponse.getResult().equals(DocWriteResponse.Result.CREATED);
    }

    /**
     * 单条更新
     *
     * @param indexName
     * @param id
     * @param data
     * @return
     * @throws IOException
     */
    public boolean updateData(String indexName, String id, Object data) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(indexName, id);
        //准备文档
        String jsonString = JSONObject.toJSONString(data);
        Map jsonMap = JSONObject.parseObject(jsonString, Map.class);
        updateRequest.doc(jsonMap);
        updateRequest.timeout(TimeValue.timeValueSeconds(1));
        updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
        //数据为存储而不是更新
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        return update.getGetResult().equals(DocWriteResponse.Result.UPDATED);
    }


    /**
     * 批量新增数据
     *
     * @param index
     * @param datas
     * @return
     */
    public boolean addBatchData(String index, List<? extends EsBaseData> datas) {
        Assert.hasLength(index, "Elasticsearch exception indexName null");
        Assert.notEmpty(datas, "addBatchData elastaicsearch exception datas is null");
        if (datas.size() > 100000) {
            log.error("es add batch data too large{}", datas.size());
            throw new BusinessException("es add batch data too large" + datas.size());
        }
        BulkResponse bulk = null;
        try {
            BulkRequest request = new BulkRequest();
            datas.forEach(data -> {
                String source = JSON.toJSONString(data);
                request.add(new IndexRequest(data.getIndexName()).id(data.esId).source(source, XContentType.JSON));
            });
            bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);

        } catch (Exception e) {
            log.error("elasticsearch addBatchData error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch addBatchData error , meassage=" + e.getMessage());
        }
        return !bulk.hasFailures();
    }

    /**
     * 通过id删除数据
     *
     * @param indexName
     * @param id
     * @return
     */
    public boolean deleteDataById(String indexName, String id) {
        DeleteRequest deleteRequest = new DeleteRequest(indexName, id);
        DeleteResponse response = null;
        try {
            response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("elasticsearch deleteDocById error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch deleteDataById error , meassage=" + e.getMessage());
        }
        return response.getResult().equals(DocWriteResponse.Result.DELETED);
    }


    /**
     * 通过条件删除数据
     *
     * @param indexName
     * @param conditionFileds
     * @return
     */
    public boolean deleteDataByCondition(String indexName, List<EsField> conditionFileds) {
        Assert.hasLength(indexName, "Elasticsearch exception indexName null");
        Assert.notEmpty(conditionFileds, "Elasticsearch exception conditionFileds null");
        BulkByScrollResponse resp = null;
        try {
            DeleteByQueryRequest request = new DeleteByQueryRequest(indexName);
//            SearchSourceBuilder searchSourceBuilder = buildSearchSourceBuilder(conditionFileds);
//            request.getSearchRequest().source(searchSourceBuilder);
            // 更新时版本冲突
            request.setConflicts("proceed");
            //构建条件
            setDeletCondition(conditionFileds, request);
            // 刷新索引
            request.setRefresh(true);

            resp = restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("elasticsearch deleteDataByCondition error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch deleteDataByCondition error , meassage=" + e.getMessage());
        }
        return resp.getStatus().getDeleted() > 0;
    }


    /**
     * 通过条件更新数据
     *
     * @param indexName
     * @param conditionFileds
     * @return
     */
    public boolean updateDataByCondition(String indexName, List<EsField> conditionFileds, Object data) {
        Assert.hasLength(indexName, "Elasticsearch exception indexName null");
        Assert.notEmpty(conditionFileds, "Elasticsearch exception conditionFileds null");
        Assert.notNull(data, "elasticsearch updateDataByCondition data is null ");
        BulkByScrollResponse resp = null;
        try {
            UpdateByQueryRequest request = new UpdateByQueryRequest(indexName);
            //设置分片并行
            request.setSlices(2);
            //设置版本冲突时继续执行
            request.setConflicts("proceed");
            //构建条件
            setUpdateConfition(conditionFileds, request);
            //设置更新完成后刷新索引 ps很重要如果不加可能数据不会实时刷新
            request.setRefresh(true);
            StringBuffer scriptContext = buildScriptContext(data);
            //设置要修改的内容可以多个值多个用;隔开
            request.setScript(new Script(scriptContext.toString()));
            resp = restHighLevelClient.updateByQuery(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("elasticsearch updateDataByCondition error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch updateDataByCondition error , meassage=" + e.getMessage());
        }
        return resp.getStatus().getUpdated() > 0;
    }

    /**
     * 根据id查询文档
     */
    public <T> T selectDataById(String indexName, String id, Class<T> c) {
        Assert.hasLength(indexName, "Elasticsearch exception indexName null");
        Assert.hasLength(id, "Elasticsearch exception id null");
        GetResponse response = null;
        try {
            //设置查询的索引、文档
            GetRequest indexRequest = new GetRequest(indexName, id);
            response = restHighLevelClient.get(indexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("elasticsearch selectDataById error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch selectDataById error , meassage=" + e.getMessage());
        }
        String res = response.getSourceAsString();
        return JSONObject.parseObject(res, c);
    }


    /**
     * 条件查询
     *
     * @param indexName
     * @param conditionFileds 条件
     * @param c               返回对象类型
     * @return
     */
    public <T> List<T> selectDataList(String indexName, List<EsField> conditionFileds, Class<T> c) {
        Assert.hasLength(indexName, "Elasticsearch exception indexName null");
        Assert.notNull(c, "Class<T>  is null ");
        List<T> res = null;
        try {
            // 创建检索请求
            SearchRequest searchRequest = new SearchRequest();
            // 指定索引
            searchRequest.indices(indexName);
            SearchSourceBuilder searchSourceBuilder = buildSearchSourceBuilder(conditionFileds);
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //分析结果
            SearchHit[] hits = searchResponse.getHits().getHits();
            res = new ArrayList<>();
            for (SearchHit hit : hits
            ) {
                String data = hit.getSourceAsString();
                T t = JSONObject.parseObject(data, c);
                log.info("data={}", data);
                res.add(t);
            }
        } catch (Exception e) {
            log.error("elasticsearch selectDataList error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch selectDataList error , meassage=" + e.getMessage());
        }
        return res;
    }

    /**
     * 条件查询
     *
     * @param indexName
     * @param conditionFileds 条件
     * @param c               返回对象类型
     * @return
     */
    public <T> EsPage<T> selectDataPage(String indexName, Integer pageNum, Integer pageSize, List<EsField> conditionFileds, Class<T> c) {
        Assert.hasLength(indexName, "Elasticsearch exception indexName null");
        Assert.notNull(c, "Class<T>  is null ");
        List<T> res = null;
        //总记录数
        Integer total = 0;
        try {
            // 创建检索请求
            SearchRequest searchRequest = new SearchRequest();
            // 指定索引
            searchRequest.indices(indexName);
            SearchSourceBuilder searchSourceBuilder = buildSearchSourceBuilder(conditionFileds);
            //设置分页

            searchSourceBuilder.from((pageNum - 1) * pageSize).size(pageSize);
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //分析结果
            SearchHit[] hits = searchResponse.getHits().getHits();
            total = new Long(searchResponse.getHits().getTotalHits().value).intValue();
            res = new ArrayList<>();
            for (SearchHit hit : hits
            ) {
                String data = hit.getSourceAsString();
                T t = JSONObject.parseObject(data, c);
                log.info("data={}", data);
                res.add(t);
            }
        } catch (Exception e) {
            log.error("elasticsearch selectDataPage error , meassage = {}", e.getMessage());
            //打印轨迹
            log.error(e.getMessage(), e);
            throw new BusinessException("elasticsearch selectDataPage error , meassage=" + e.getMessage());
        }
        return new EsPage<>(pageNum, pageSize, total, res);
    }

    /**
     * 创建搜索条件
     *
     * @param conditionFileds
     * @return
     */
    private static SearchSourceBuilder buildSearchSourceBuilder(List<EsField> conditionFileds) {
        // 指定DSL
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建条件
        if (!CollectionUtils.isEmpty(conditionFileds)) {
            for (EsField condFiled :
                    conditionFileds) {
                switch (condFiled.getFieldTypeEnum()) {
                    case ORDER_ASC:
                        //升序
                        searchSourceBuilder.sort(condFiled.getField(), SortOrder.ASC);
                        break;
                    case ORDER_ESC:
                        //降序
                        searchSourceBuilder.sort(condFiled.getField(), SortOrder.DESC);
                        break;
                    case VAGUE_QUERY:
                        // 模糊查询
                        searchSourceBuilder.query(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()).fuzziness(Fuzziness.AUTO));
                        break;
                    case PRECISE_QUERY:
                        searchSourceBuilder.query(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()));
                        break;
                    default:
                        //默认精准查询
                        searchSourceBuilder.query(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()));
                        break;
                }
            }
        }
        return searchSourceBuilder;
    }


    /**
     * 构建删除条件
     *
     * @param conditionFileds
     * @param request
     */
    private void setDeletCondition(List<EsField> conditionFileds, DeleteByQueryRequest request) {
        if (!CollectionUtils.isEmpty(conditionFileds)) {
            for (EsField condFiled :
                    conditionFileds) {
                switch (condFiled.getFieldTypeEnum()) {
                    case VAGUE_QUERY:
//                           模糊查询
                        request.setQuery(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()).fuzziness(Fuzziness.AUTO));
                        break;
                    case PRECISE_QUERY:
                        request.setQuery(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()));
                        break;
                    default:
                        log.error("field type error ,only supprt VAGUE_QUERY and PRECISE_QUERY");
                        throw new BusinessException(" field type error ,only supprt VAGUE_QUERY and PRECISE_QUERY");
                }
            }
        }
    }

    /**
     * 构建修改条件
     *
     * @param conditionFileds
     * @param request
     */
    private void setUpdateConfition(List<EsField> conditionFileds, UpdateByQueryRequest request) {
        if (!CollectionUtils.isEmpty(conditionFileds)) {
            for (EsField condFiled :
                    conditionFileds) {
                switch (condFiled.getFieldTypeEnum()) {
                    case VAGUE_QUERY:
//                           模糊查询
                        request.setQuery(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()).fuzziness(Fuzziness.AUTO));
                        break;
                    case PRECISE_QUERY:
                        request.setQuery(QueryBuilders.matchQuery(condFiled.getField(), condFiled.getValue()));
                        break;
                    default:
                        log.error("field type error ,only supprt VAGUE_QUERY and PRECISE_QUERY");
                        throw new BusinessException(" field type error ,only supprt VAGUE_QUERY and PRECISE_QUERY");
                }
            }
        }
    }


    /**
     * 创建修改script内容
     *
     * @param data
     * @return
     */
    private StringBuffer buildScriptContext(Object data) {
        //准备文档
        String jsonString = JSONObject.toJSONString(data);
        Map<String, String> jsonMap = JSONObject.parseObject(jsonString, Map.class);
        String tem = "ctx._source['key']='value'";
        StringBuffer scriptContext = new StringBuffer();
        for (String key :
                jsonMap.keySet()) {
            String value = jsonMap.get(key);
            scriptContext.append(tem.replace("key", key).replace("value", value))
                    .append(";");

        }
        return scriptContext;
    }
}

其他辅助嘞

Es基础对象

package cn.hsa.utils.elasticsearch;

import lombok.Data;

/**
 * Es基础对象
 * @author lsj
 * @date 2021/11/8 13:57
 */
@Data
public class EsBaseData {
    //索引
    public String indexName;
    //id
    public String esId;
}

查询条件对象

package cn.hsa.utils.elasticsearch;

import lombok.Data;

/**
 * 查询条件对象
 * @author lsj
 * @date 2021/11/8 12:53
 */
@Data
public class EsField {
    //字段对应操作功能
    private FieldTypeEnum fieldTypeEnum;
    //字段名称
    private String field;
    //字段对应的值
    private String value;
    public EsField(){

    }
    public EsField(String field ,String value , FieldTypeEnum fieldTypeEnum){
        this.value = value;
        this.field = field;
        this.fieldTypeEnum  = fieldTypeEnum;
    }
}

分页对象

package cn.hsa.utils.elasticsearch;

import org.springframework.util.CollectionUtils;

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

/**
 * @author lsj
 * @date 2021/11/3 14:53
 */
public class EsPage<T> {

    //当前页的数量
    private int size;

    /**
     * 当前页
     */
    private int pageNum;
    /**
     * 每页显示多少条
     */
    private int pageSize;

    /**
     * 总记录数
     */
    private int total;
    /**
     * 本页的数据列表
     */
    private List<T> list;

    /**
     * 总页数
     */
    private int pages;
    /**
     * 页码列表的开始索引(包含)
     */
    private int beginPageIndex;
    /**
     * 页码列表的结束索引(包含)
     */
    private int endPageIndex;

    /**
     * 只接受前4个必要的属性,会自动的计算出其他3个属性的值
     *
     * @param pageNum
     * @param pageSize
     * @param total
     * @param list
     */
    public EsPage(int pageNum, int pageSize, int total, List<T> list) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.total = total;
        this.list = list;
        this.size = CollectionUtils.isEmpty(list)?0:list.size();
        // 计算总页码
        pages =pageSize==0?0:(total + pageSize - 1) / pageSize;

        // 计算 beginPageIndex 和 endPageIndex
        // >> 总页数不多于10页,则全部显示
        if (pages <= 10) {
            beginPageIndex = 1;
            endPageIndex = pages;
        }
        // >> 总页数多于10页,则显示当前页附近的共10个页码
        else {
            // 当前页附近的共10个页码(前4个 + 当前页 + 后5个)
            beginPageIndex = pageNum - 4;
            endPageIndex = pageNum + 5;
            // 当前面的页码不足4个时,则显示前10个页码
            if (beginPageIndex < 1) {
                beginPageIndex = 1;
                endPageIndex = 10;
            }
            // 当后面的页码不足5个时,则显示后10个页码
            if (endPageIndex > pages) {
                endPageIndex = pages;
                beginPageIndex = pages - 10 + 1;
            }
        }
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }


    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public int getBeginPageIndex() {
        return beginPageIndex;
    }

    public void setBeginPageIndex(int beginPageIndex) {
        this.beginPageIndex = beginPageIndex;
    }

    public int getEndPageIndex() {
        return endPageIndex;
    }

    public void setEndPageIndex(int endPageIndex) {
        this.endPageIndex = endPageIndex;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }
}

条件数据类型枚举

package cn.hsa.utils.elasticsearch;

/**
 * 条件数据类型
 * @author lsj
 * @date 2021/11/8 12:54
 */
public enum FieldTypeEnum {
    //精准查询
    PRECISE_QUERY,
    //模糊查询
    VAGUE_QUERY,
    //排序_升序
    ORDER_ASC,
    //排序_降序
    ORDER_ESC
    ;
}

父maven依赖

 <elasticsearch.version>7.2.0</elasticsearch.version> 
<dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>${elasticsearch.version}</version>
            </dependency>

            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>${elasticsearch.version}</version>
            </dependency>

            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-client</artifactId>
                <version>${elasticsearch.version}</version>
            </dependency>     
   

子maven依赖

   <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
        </dependency>

测试类

package cn.hsa.csc.query.service.es;

import cn.hsa.csc.query.dto.PageDTO;
import cn.hsa.hsaf.core.framework.web.HsafRestPath;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hsa.utils.elasticsearch.*;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@HsafRestPath(value = "/api/Es")
@Service
public class EsTestService {
    @Autowired
    ElasticsearchUtils elasticsearchUtils;

    /**
     * @return
     */
    @HsafRestPath(value = "/add", method = RequestMethod.POST)
    public WrapperResponse add(EsObj esObj) {
//        Map<String, Object> jsonMap = new HashMap<>();
//        jsonMap.put("name", "spring cloud实战");
//        jsonMap.put("description", "本课程主要从四个章节进行讲解:1.微服务架构入门。2.spring cloud 实战。3.实战spring。4.。。");
//        jsonMap.put("studymodel", "201001");
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        jsonMap.put("timestamp", dateFormat.format(new Date()));
//        jsonMap.put("price", 5.6f);
        boolean b = elasticsearchUtils.addData(esObj.getIndexName(), UUID.randomUUID().toString(), esObj.getDta());
        return WrapperResponse.success(b);
    }


    /**
     * getDataById
     *
     * @return
     */
    @HsafRestPath(value = "/getDataById", method = RequestMethod.POST)
    public WrapperResponse getDataById(EsObj esObj) {
        EsTestRes doc = elasticsearchUtils.selectDataById(esObj.getIndexName(), esObj.getId(), EsTestRes.class);
        return WrapperResponse.success(doc);
    }


    /**
     * getDataByCondition
     *
     * @return
     */
    @HsafRestPath(value = "/getDataByCondition", method = RequestMethod.POST)
    public WrapperResponse getDataByCondition(EsObj esObj) {
        List<EsField> conditionFileds = new ArrayList<>();
        if (esObj.getDta() != null) {
            String s = JSONObject.toJSONString(esObj.getDta());
            EsTestRes esTestRes = JSONObject.parseObject(s, EsTestRes.class);
            conditionFileds.add(new EsField("name", esTestRes.getName(), FieldTypeEnum.VAGUE_QUERY));
        }

        EsPage<EsTestRes> list = elasticsearchUtils.selectDataPage(esObj.getIndexName(),esObj.getPageNo(),esObj.getPageSize(), conditionFileds, EsTestRes.class);
        return WrapperResponse.success(list);
    }

    /**
     * getDataByCondition
     *
     * @return
     */
    @HsafRestPath(value = "/addOrUpdateData", method = RequestMethod.POST)
    public WrapperResponse addOrUpdateData(EsObj esObj) {
        boolean b = elasticsearchUtils.addOrUpdateData(esObj.getIndexName(), esObj.getId(), esObj.getDta());
        return WrapperResponse.success(b);
    }

    /**
     * getDataByCondition
     *
     * @return
     */
    @HsafRestPath(value = "/addBatchData", method = RequestMethod.POST)
    public WrapperResponse addBatchData(EsObj esObj) {
        List<EsTestRes> datas = new ArrayList<>();
        datas.add(new EsTestRes(UUID.randomUUID().toString(), esObj.getIndexName(), "5.5", "201001", "张三", "你说啥就是啥1"));
        datas.add(new EsTestRes(UUID.randomUUID().toString(), esObj.getIndexName(), "6.5", "201002", "张三", "你说啥就是啥2"));
        datas.add(new EsTestRes(UUID.randomUUID().toString(), esObj.getIndexName(), "7.5", "201003", "张三", "你说啥就是啥3"));
        datas.add(new EsTestRes(UUID.randomUUID().toString(), esObj.getIndexName(), "8.5", "201004", "张三", "你说啥就是啥4"));
        boolean b = elasticsearchUtils.addBatchData(esObj.getIndexName(), datas);
        return WrapperResponse.success(b);
    }

    /**
     * deleteDataById
     *
     * @return
     */
    @HsafRestPath(value = "/deleteDataByCondition", method = RequestMethod.POST)
    public WrapperResponse deleteDataByCondition(EsObj esObj) {
        List<EsField> conditionFileds = new ArrayList<>();
        if (esObj.getDta() != null) {
            String s = JSONObject.toJSONString(esObj.getDta());
            EsTestRes esTestRes = JSONObject.parseObject(s, EsTestRes.class);
            conditionFileds.add(new EsField("name", esTestRes.getName(), FieldTypeEnum.VAGUE_QUERY));
        }
        boolean b = elasticsearchUtils.deleteDataByCondition(esObj.getIndexName(), conditionFileds);
        return WrapperResponse.success(b);
    }


    /**
     * deleteDataById
     *
     * @return
     */
    @HsafRestPath(value = "/updateDataByCondition", method = RequestMethod.POST)
    public WrapperResponse updateDataByCondition(EsObj esObj) {
        List<EsField> conditionFileds = new ArrayList<>();
        if (esObj.getDta() != null) {
            String s = JSONObject.toJSONString(esObj.getDta());
            EsTestRes esTestRes = JSONObject.parseObject(s, EsTestRes.class);
            conditionFileds.add(new EsField("name", esTestRes.getName(), FieldTypeEnum.VAGUE_QUERY));
        }
        boolean b = elasticsearchUtils.updateDataByCondition(esObj.getIndexName(), conditionFileds,new EsTestRes("1","2","王五","4"));
        return WrapperResponse.success(b);
    }


    /**
     * deleteDataById
     *
     * @return
     */
    @HsafRestPath(value = "/deleteDataById", method = RequestMethod.POST)
    public WrapperResponse deleteDataById(EsObj esObj) {
        boolean b = elasticsearchUtils.deleteDataById(esObj.getIndexName(), esObj.getId());
        return WrapperResponse.success(b);
    }

    @Data
    public static class EsObj extends PageDTO {
        private String indexName;
        private String typeName;
        private String id;
        private Object dta;
    }

    @Data
    public static class EsTestRes extends EsBaseData {
        private String price;
        private String studymodel;
        private String name;
        private String description;

        public EsTestRes() {
        }

        public EsTestRes(String esId, String idexName, String price, String studymodel, String name, String description) {
            this.esId = esId;
            this.indexName = idexName;
            this.price = price;
            this.studymodel = studymodel;
            this.name = name;
            this.description = description;
        }

        public EsTestRes(String price, String studymodel, String name, String description) {
            this.price = price;
            this.studymodel = studymodel;
            this.name = name;
            this.description = description;
        }
    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐