Springboot+elasticsearch客户端

Springboot+elasticsearch客户端

一、 ES客户端
  ES提供多种不同的客户端:
    1、TransportClient
    ES提供的传统客户端,官方计划8.0版本删除此客户端。
    2、RestClient
    RestClient是官方推荐使用的,它包括两种:Java Low Level REST Client和 Java High Level REST Client。ES在6.0之后提供 Java High Level REST Client, 两种客户端官方更推荐使用 Java High Level REST Client,不过当前它还处于完善中,有些功能还没有。
本次采用 Java High Level REST Client,如果它有不支持的功能,则使用Java Low Level REST Client。
Java High Level REST Client:Java高级别REST客户端
注意:在使用过程中注意API依赖与elasticsearch库的版本一致,elasticsearch_7.X之后开始弃用索引类型(_type),并且索引与索引类型一一对应。多看源码!!!
依赖:

<!--ES依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.4.0</version>
        </dependency>

工具类:

package net.pushi.neo4jdata.util;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ElasticUtil {

    private ElasticUtil(){}

    public static Class<?> getClazz(String clazzName){
        try {
            return Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * @date 2020/3/26 10:01
     * @param queryBuilder  设置查询对象
     * @param from  设置from选项,确定要开始搜索的结果索引。 默认为0。
     * @param size  设置大小选项,确定要返回的搜索匹配数。 默认为10。
     * @param timeout
     * @return org.elasticsearch.search.builder.SearchSourceBuilder
     * @throws
     * @since
     */
    public static SearchSourceBuilder initSearchSourceBuilder(QueryBuilder queryBuilder, int from, int size, int timeout){

        //使用默认选项创建 SearchSourceBuilder 。
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //设置查询对象。可以使任何类型的 QueryBuilder
        sourceBuilder.query(queryBuilder);
        //设置from选项,确定要开始搜索的结果索引。 默认为0。
        sourceBuilder.from(from);
        //设置大小选项,确定要返回的搜索匹配数。 默认为10。
        sourceBuilder.size(size);
        sourceBuilder.timeout(new TimeValue(timeout, TimeUnit.SECONDS));
        return sourceBuilder;
    }

    /**
     * @date 2020/3/26 10:01
     * @param queryBuilder
     * @return org.elasticsearch.search.builder.SearchSourceBuilder
     * @throws
     * @since
     */
    public static SearchSourceBuilder initSearchSourceBuilder(QueryBuilder queryBuilder){
        return initSearchSourceBuilder(queryBuilder,0,10,60);
    }
}

数据存储对象:

package net.pushi.neo4jdata.dataParser.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;

/**
 * @ClassName ElasticEntity
 * @Description  数据存储对象
 * @author hsy
 * @date 2020/4/1 10:10
 * @Version 1.0.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ElasticEntity<T> {

    /**
     * 主键标识,用户ES持久化
     */
    private String id;

    /**
     * JSON对象,实际存储数据
     */
    private Map data;
}

交互对象:

package net.pushi.neo4jdata.dataParser.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.pushi.neo4jdata.dataParser.entity.ElasticEntity;

/**
 * @ClassName ElasticDataVo
 * @Description http交互Vo对象
 * @author hsy
 * @date 2020/4/1 10:10
 * @Version 1.0.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ElasticDataVo<T> {

    /**
     * 索引名
     */
    private String idxName;
    /**
     * 数据存储对象
     */
    private ElasticEntity elasticEntity;

}

交互对象集:

package net.pushi.neo4jdata.dataParser.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.pushi.neo4jdata.dataParser.entity.ElasticEntity;

import java.util.List;

/**
 * @ClassName ElasticDataVo
 * @Description http交互Vo对象集
 * @author hsy
 * @date 2020/4/1 10:10
 * @Version 1.0.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ElasticDatasVo<T> {

    /**
     * 索引名
     */
    private String idxName;

    private String type;
    /**
     * 数据存储对象集
     */
    private List<ElasticEntity> elasticEntities;

}

索引管理代码:

package net.pushi.neo4jdata.dataParser.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.pushi.neo4jdata.dataParser.service.impl.BaseElasticService;
import net.pushi.neo4jdata.dataParser.vo.IdxVo;
import net.pushi.neo4jdata.message.enums.ResponseCode;
import net.pushi.neo4jdata.message.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName ElasticIndexController
 * @Description ElasticSearch索引的基本管理,提供对外查询、删除和新增功能
 * @author hsy
 * @date 2020/4/1 11:22
 * @Version 1.0.0
 */
@Slf4j
@RequestMapping("/elastic")
@RestController
public class ElasticIndexController {

    @Autowired
    BaseElasticService baseElasticService;

    @GetMapping(value = "/")
    public ResponseResult index(String index){
        return new ResponseResult();
    }

    /**
     * @Description 创建Elastic索引
     * @param idxVo
     * @return net.pushi.neo4jdata.message.response.ResponseResult
     * @throws
     * @date 2020/4/1 11:22
     */
    @PostMapping(value = "/createIndex")
    public ResponseResult createIndex(@RequestBody IdxVo idxVo){
        ResponseResult response = new ResponseResult();
        try {
            //索引不存在,再创建,否则不允许创建
            if(!baseElasticService.isExistsIndex(idxVo.getIdxName())){
                String idxSql = JSON.toJSONString(idxVo.getIdxSql());
                log.warn(" idxName={}, idxSql={}",idxVo.getIdxName(),idxSql);
                baseElasticService.createIndex(idxVo.getIdxName(),idxSql);
            } else{
                response.setStatus(false);
                response.setCode(ResponseCode.DUPLICATEKEY_ERROR_CODE.getCode());
                response.setMsg("索引已经存在,不允许创建");
            }
        } catch (Exception e) {
            response.setStatus(false);
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMsg(ResponseCode.ERROR.getMsg());
        }
        return response;
    }

    /**
     * @Description 判断索引是否存在;存在-TRUE,否则-FALSE
     * @param index
     * @return net.pushi.neo4jdata.message.response.ResponseResult
     * @throws
     * @date 2020/4/1 11:22
     */
    @GetMapping(value = "/exist/{index}")
    public ResponseResult indexExist(@PathVariable(value = "index") String index){
        ResponseResult response = new ResponseResult();
        try {
            if(!baseElasticService.isExistsIndex(index)){
                log.error("index={},不存在",index);
                response.setCode(ResponseCode.RESOURCE_NOT_EXIST.getCode());
                response.setMsg(ResponseCode.RESOURCE_NOT_EXIST.getMsg());
            } else {
                response.setMsg(" 索引已经存在, " + index);
            }
        } catch (Exception e) {
            response.setCode(ResponseCode.NETWORK_ERROR.getCode());
            response.setMsg(" 调用ElasticSearch 失败!");
            response.setStatus(false);
        }
        return response;
    }

    //删除索引
    @GetMapping(value = "/del/{index}")
    public ResponseResult indexDel(@PathVariable(value = "index") String index){
        ResponseResult response = new ResponseResult();
        try {
            baseElasticService.deleteIndex(index);
        } catch (Exception e) {
            response.setCode(ResponseCode.NETWORK_ERROR.getCode());
            response.setMsg(" 调用ElasticSearch 失败!");
            response.setStatus(false);
        }
        return response;
    }
}

数据管理代码:

package net.pushi.neo4jdata.dataParser.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.pushi.neo4jdata.dataParser.entity.ElasticEntity;
import net.pushi.neo4jdata.dataParser.entity.Location;
import net.pushi.neo4jdata.dataParser.service.impl.BaseElasticService;
import net.pushi.neo4jdata.dataParser.service.impl.LocationService;
import net.pushi.neo4jdata.dataParser.vo.ElasticDataVo;
import net.pushi.neo4jdata.dataParser.vo.ElasticDatasVo;
import net.pushi.neo4jdata.dataParser.vo.QueryVo;
import net.pushi.neo4jdata.message.enums.ResponseCode;
import net.pushi.neo4jdata.message.response.ResponseResult;
import net.pushi.neo4jdata.util.ElasticUtil;
import net.pushi.neo4jdata.util.StringUtils;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/** 数据管理
 * @ClassName ElasticMgrController
 * @author hsy
 * @date 2020/4/8 10:55
 * @Version 1.0.0
 */
@Slf4j
@RequestMapping("/elasticMgr")
@RestController
public class ElasticMgrController {

    @Autowired
    private BaseElasticService baseElasticService;

    @Autowired
    LocationService locationService;

    /**
     * @Description 批量新增
     * @param elasticDatasVo
     * @return net.pushi.neo4jdata.message.response.ResponseResult
     * @date 2020/4/8 16:55
     */
    //ES库7.X版本之后索引与索引类型一一对应
    @PostMapping(value = "/adds")
    public ResponseResult adds(@RequestBody ElasticDatasVo elasticDatasVo){
        ResponseResult response = getResponseResult();
        try {
            if(!StringUtils.isNotEmpty(elasticDatasVo.getIdxName())){
                response.setCode(ResponseCode.PARAM_ERROR_CODE.getCode());
                response.setMsg("索引为空,不允许提交");
                response.setStatus(false);
                log.warn("索引为空");
                return response;
            }
            //List<ElasticEntity> entityList = new ArrayList<>();
            List<ElasticEntity> entities = elasticDatasVo.getElasticEntities();
            /*for (ElasticEntity entity : entities){
                ElasticEntity elasticEntity = new ElasticEntity();
                elasticEntity.setId(entity.getId());
                elasticEntity.setData(entity.getData());
                entityList.add(elasticEntity);
            }*/
            baseElasticService.adds(elasticDatasVo.getIdxName(),elasticDatasVo.getType(),entities);
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    /**
     * @Description 新增数据
     * @param elasticDataVo
     * @return net.pushi.neo4jdata.message.response.ResponseResult
     * @date 2020/4/8 10:55
     */
    @PostMapping(value = "/add")
    public ResponseResult add(@RequestBody ElasticDataVo elasticDataVo){
        ResponseResult response = getResponseResult();
        try {
            if(!StringUtils.isNotEmpty(elasticDataVo.getIdxName())){
                response.setCode(ResponseCode.PARAM_ERROR_CODE.getCode());
                response.setMsg("索引为空,不允许提交");
                response.setStatus(false);
                log.warn("索引为空");
                return response;
            }
            ElasticEntity elasticEntity = new ElasticEntity();
            elasticEntity.setId(elasticDataVo.getElasticEntity().getId());
            elasticEntity.setData(elasticDataVo.getElasticEntity().getData());
            baseElasticService.insertOrUpdateOne(elasticDataVo.getIdxName(), elasticEntity);
        } catch (Exception e) {
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMsg(ResponseCode.ERROR.getMsg());
            response.setStatus(false);
            log.error("插入数据异常,metadataVo={},异常信息={}", elasticDataVo.toString(),e.getMessage());
        }
        return response;
    }

    /**
     * @Description 删除
     * @param elasticDataVo
     * @return net.pushi.neo4jdata.message.response.ResponseResult
     * @date 2020/4/8 10:55
     */
    @PostMapping(value = "/delete")
    public ResponseResult delete(@RequestBody ElasticDataVo elasticDataVo){
        ResponseResult response = getResponseResult();
        try {
            if(!StringUtils.isNotEmpty(elasticDataVo.getIdxName())){
                response.setCode(ResponseCode.PARAM_ERROR_CODE.getCode());
                response.setMsg("索引为空,不允许提交");
                response.setStatus(false);
                log.warn("索引为空");
                return response;
            }
            baseElasticService.deleteOne(elasticDataVo.getIdxName(),elasticDataVo.getElasticEntity());
        } catch (Exception e) {
            log.error("删除数据失败");
        }
        return response;
    }

    /**
     * @param index 初始化Location区域,写入数据。
     * @return net.pushi.neo4jdata.message.response.ResponseResult
     * @date 2020/4/8 10:55
     */
    @GetMapping(value = "/addLocation/{index}")
    public ResponseResult addLocation(@PathVariable(value = "index") String index){
        ResponseResult response = getResponseResult();
        try {
            for(int lv=0;lv<4;lv++){
                addLocationPage(1,100,index,lv);
            }

        } catch (Exception e) {
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMsg("服务忙,请稍后再试");
            response.setStatus(false);
        }
        return response;
    }

    public void addLocationPage(int pageNum,int pageSize,String index,int lv){
        Location location = new Location();
        location.setLv(lv);
        PageHelper.startPage(pageNum, pageSize);
        List<Location> locations = locationService.getList2(location);
        PageInfo pageInfo = new PageInfo(locations);
        if(!pageInfo.getList().isEmpty()){
            log.error("第{}层级,第{}页,开始入ES库",lv,pageNum);
            insertDatas(index,locations);
            if(pageInfo.isHasNextPage()){
                addLocationPage(pageInfo.getNextPage(),pageSize,index,lv);
            }
        }
    }

    public void insertDatas(String idxName,List<Location> locations){
        List<ElasticEntity> elasticEntitys = new ArrayList<ElasticEntity>(locations.size());
        for(Location _loca:locations){
            ElasticEntity elasticEntity = new ElasticEntity();
            elasticEntity.setId(_loca.getId().toString());
//            elasticEntity.setData(gson.toJson(_loca));
//            elasticEntitys.add(elasticEntity);
//            log.error(_loca.toString());
        }
        baseElasticService.insertBatch(idxName,elasticEntitys);
    }

    /**
     * @param queryVo 查询实体对象
     * @return net.pushi.neo4jdata.message.response.ResponseResult
     * @date 2020/4/8 10:55
     */
    @GetMapping(value = "/get")
    public ResponseResult get(@RequestBody QueryVo queryVo){

        ResponseResult response = getResponseResult();

        if(!StringUtils.isNotEmpty(queryVo.getIdxName())){
            response.setCode(ResponseCode.PARAM_ERROR_CODE.getCode());
            response.setMsg("索引为空,不允许提交");
            response.setStatus(false);
            log.warn("索引为空");
            return response;
        }

        try {
            Class<?> clazz = ElasticUtil.getClazz(queryVo.getClassName());
            Map<String,Object> params = queryVo.getQuery().get("match");
            Set<String> keys = params.keySet();
            MatchQueryBuilder queryBuilders=null;
            for(String ke:keys){
                queryBuilders = QueryBuilders.matchQuery(ke, params.get(ke));
            }
            if(null!=queryBuilders){
                SearchSourceBuilder searchSourceBuilder = ElasticUtil.initSearchSourceBuilder(queryBuilders);
                List<?> data = baseElasticService.search(queryVo.getIdxName(),searchSourceBuilder,clazz);
                response.setData(data);
            }
        } catch (Exception e) {
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMsg("服务忙,请稍后再试");
            response.setStatus(false);
            log.error("查询数据异常,metadataVo={},异常信息={}", queryVo.toString(),e.getMessage());
        }
        return response;
    }

    public ResponseResult getResponseResult(){
        return new ResponseResult();
    }
}

service代码:

package net.pushi.neo4jdata.dataParser.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.pushi.neo4jdata.dataParser.entity.ElasticEntity;
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.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.IndicesOptions;
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.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Slf4j
@Component
public class BaseElasticService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /** 创建索引
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName   索引名称
     * @param idxSQL    索引描述
     * @return void
     */
    public void createIndex(String idxName,String idxSQL){
        try {
            if (!this.indexExist(idxName)) {
                log.error(" idxName={} 已经存在,idxSql={}",idxName,idxSQL);
                return;
            }
            CreateIndexRequest request = new CreateIndexRequest(idxName);
            buildSetting(request);
            request.mapping(idxSQL, XContentType.JSON);
//            request.settings() 手工指定Setting
            CreateIndexResponse res = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            if (!res.isAcknowledged()) {
                throw new RuntimeException("初始化失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }

    /** 判断某个index是否存在
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName index名
     * @return boolean
     */
    public boolean indexExist(String idxName) throws Exception {
        GetIndexRequest request = new GetIndexRequest(idxName);
        request.local(false);
        request.humanReadable(true);
        request.includeDefaults(false);
        request.indicesOptions(IndicesOptions.lenientExpandOpen());
        return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
    }

    /** 判断某个index是否存在
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName index名
     * @return boolean
     */
    public boolean isExistsIndex(String idxName) throws Exception {
        return restHighLevelClient.indices().exists(new GetIndexRequest(idxName),RequestOptions.DEFAULT);
    }

    /** 设置分片
     * @author hsy
     * @date 2020/4/7 17:30
     * @param request
     * @return void
     */
    public void buildSetting(CreateIndexRequest request){
        request.settings(Settings.builder().put("index.number_of_shards",3)
                .put("index.number_of_replicas",2));
    }

    //批量新增
    public void adds(String idxName, String type, List<ElasticEntity> list){
        BulkRequest request = new BulkRequest();
        list.forEach(item -> request.add(new IndexRequest(idxName,type).id(item.getId()).source(JSON.toJSONString(item.getData()), XContentType.JSON)));
        try {
            restHighLevelClient.bulk(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /** 单个更新
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName index
     * @param entity  对象
     * @return void
     */
    public void insertOrUpdateOne(String idxName, ElasticEntity entity) {
        IndexRequest request = new IndexRequest(idxName);
        log.error("Data : id={},entity={}",entity.getId(),JSON.toJSONString(entity.getData()));
        request.id(entity.getId());
//        request.source(entity.getData(), XContentType.JSON);
        request.source(JSON.toJSONString(entity.getData()), XContentType.JSON);
        try {
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /** 单个删除
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName index
     * @param entity  对象
     * @return void
     */
    public void deleteOne(String idxName, ElasticEntity entity) {
        DeleteRequest request = new DeleteRequest(idxName);
        request.id(entity.getId());
        try {
            restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /** 批量插入
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName index
     * @param list 待插入列表
     * @return void
     */
    public void insertBatch(String idxName, List<ElasticEntity> list) {
        BulkRequest request = new BulkRequest();
        list.forEach(item -> request.add(new IndexRequest(idxName).id(item.getId()).source(JSON.toJSONString(item.getData()), XContentType.JSON)));
        try {
            restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /** 批量插入
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName index
     * @param list 待插入列表
     * @return void
     */
    public void insertBatchTrueObj(String idxName, List<ElasticEntity> list) {
        BulkRequest request = new BulkRequest();
        list.forEach(item -> request.add(new IndexRequest(idxName).id(item.getId()).source(item.getData(), XContentType.JSON)));
        try {
            restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /** 批量删除
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName index
     * @param idList  待删除列表
     * @return void
     */
    public <T> void deleteBatch(String idxName, Collection<T> idList) {
        BulkRequest request = new BulkRequest();
        idList.forEach(item -> request.add(new DeleteRequest(idxName, item.toString())));
        try {
            restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /** 批量查询
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName index
     * @param builder   查询参数
     * @param c 结果类对象
     * @return java.util.List<T>
     */
    public <T> List<T> search(String idxName, SearchSourceBuilder builder, Class<T> c) {
        SearchRequest request = new SearchRequest(idxName);
        request.source(builder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            List<T> res = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                res.add(JSON.parseObject(hit.getSourceAsString(), c));
            }
            return res;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /** 删除index
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName
     * @return void
     */
    public void deleteIndex(String idxName) {
        try {
            if (!this.indexExist(idxName)) {
                log.error(" idxName={} 已经存在",idxName);
                return;
            }
            restHighLevelClient.indices().delete(new DeleteIndexRequest(idxName), RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /** 按条件删除
     * @author hsy
     * @date 2020/4/7 17:30
     * @param idxName
     * @param builder
     * @return void
     */
    public void deleteByQuery(String idxName, QueryBuilder builder) {

        DeleteByQueryRequest request = new DeleteByQueryRequest(idxName);
        request.setQuery(builder);
        //设置批量操作数量,最大为10000
        request.setBatchSize(10000);
        request.setConflicts("proceed");
        try {
            restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/RookieCode/article/details/105435099