zoukankan      html  css  js  c++  java
  • SpringBoot 整合es(elasticsearch)使用elasticsearch-rest-high-level-client实现增删改

    引入依赖

     <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
    
    
            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>7.8.0</version>
            </dependency>
            <!-- elasticsearch的客户端 -->
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>7.8.0</version>
            </dependency>
            <!-- elasticsearch依赖2.x的log4j -->
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-api</artifactId>
                <version>2.8.2</version>
            </dependency>
    
            <!-- 阿里JSON解析器 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.75</version>
            </dependency>

    yml文件

    #elasticsearch
    esHostName: 192.168.1.25
    esPort: 9200
    ContentModel.java  根据自己的实际业务来
    import lombok.Data;
    import lombok.ToString;
    import lombok.experimental.Accessors;
    
    
    /**
     * es存放实体类
     */
    @Data
    @Accessors(chain = true)
    @ToString
    public class ContentModel {
    
        private static final long serialVersionUID = 6320548148250372657L;
    
        private Integer contentId;
    
        private String title;
    
    
    }

    配置类

    EsConfig.java

    import org.apache.http.HttpHost;
    import org.elasticsearch.client.RequestOptions;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestClientBuilder;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @author yvioo。
     */
    @Configuration
    public class EsConfig {
    
    
        @Value("${esHostName}")
        private String esHostName;
    
        @Value("${esPort}")
        private Integer esPort;
    
    
        public static final RequestOptions COMMON_OPTIONS;
    
        static {
            RequestOptions.Builder builder=RequestOptions.DEFAULT.toBuilder();
            COMMON_OPTIONS=builder.build();
        }
    
        @Bean
        public RestHighLevelClient esRestClient(){
            RestClientBuilder builder = RestClient.builder(new HttpHost(esHostName, esPort, "http"));
            RestHighLevelClient client=new RestHighLevelClient(builder);
            return client;
        }
    }

    常量

    EsConstant.java  可以不用

    /**
     * @author yvioo。
     */
    public class EsConstant {
    
        public static final String CONTENT_INDEX="索引名称";
    
    
        public static final String CONTENT_TYPE="类型";
    
    }

    工具类

    EsService.java

    import com.alibaba.fastjson.JSON;
    import com.example.es.elasticsearch.entity.ContentModel;
    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.delete.DeleteResponse;
    import org.elasticsearch.action.get.GetRequest;
    import org.elasticsearch.action.index.IndexRequest;
    import org.elasticsearch.action.update.UpdateRequest;
    import org.elasticsearch.action.update.UpdateResponse;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.elasticsearch.common.xcontent.XContentType;
    import org.elasticsearch.rest.RestStatus;
    import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    import java.io.IOException;
    import java.util.*;
    import java.util.stream.Collectors;
    
    /**
     * es操作类
     *
     * @author 洪。
     */
    @Slf4j
    @Service
    public class EsService {
    
    
        @Resource
        private RestHighLevelClient restHighLevelClient;
    
    
        /**
         * 批量插入文档数据
         * @return 返回true 表示有错误
         */
        public boolean batchEsContent(List<ContentModel> contentModelList) throws IOException {
    
            BulkRequest bulkRequest = new BulkRequest();
            List<Integer> delIds=new LinkedList<>();
    
            for (ContentModel model : contentModelList) {
                IndexRequest indexRequest = new IndexRequest(EsConstant.CONTENT_INDEX).type(EsConstant.CONTENT_TYPE);
                indexRequest.id(model.getContentId().toString());
                String s = JSON.toJSONString(model);
                indexRequest.source(s, XContentType.JSON);
                bulkRequest.add(indexRequest);
    
            }
    
    
    
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
    
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("内容索引生成:{}", collect);
            return bulk.hasFailures();
        }
    
    
        /**
         * 判断是否存在文档数据
         *
         * @param id 索引的ID
         * @return
         * @throws IOException
         */
        public boolean existIndex(Integer id) throws IOException {
            GetRequest getRequest = new GetRequest(
                    EsConstant.CONTENT_INDEX,
                    id.toString());
            getRequest.fetchSourceContext(new FetchSourceContext(false));
            getRequest.storedFields("_none_");
            return restHighLevelClient.exists(getRequest, EsConfig.COMMON_OPTIONS);
        }
    
    
        /**
         * 删除文档数据
         * @param id
         * @return
         * @throws IOException
         */
        public boolean deleteIndex(Integer id) throws IOException {
            DeleteRequest request = new DeleteRequest(
                    EsConstant.CONTENT_INDEX,
                    id.toString());
            DeleteResponse deleteResponse = restHighLevelClient.delete(
                    request,  EsConfig.COMMON_OPTIONS);
            if (deleteResponse.status().getStatus()== RestStatus.OK.getStatus()){
                return true;
            }
            return false;
        }
    
    
        /**
         * 批量删除索引
         * @param ids
         * @return 返回true 表示有错误
         * @throws IOException
         */
        public boolean deleteBatchIndex(List<Integer> ids) throws IOException {
    
            // 批量删除数据
            BulkRequest request = new BulkRequest();
    
            ids.forEach(s->{
                request.add(new DeleteRequest().index(EsConstant.CONTENT_INDEX).type(EsConstant.CONTENT_TYPE).id(s.toString()));
            });
    
    
            BulkResponse response = restHighLevelClient.bulk(request, EsConfig.COMMON_OPTIONS);
            return response.hasFailures();
        }
    
    
        /**
         * 更新文档数据
         * @param contentModel
         * @return
         * @throws IOException
         */
        public boolean updateIndex(ContentModel contentModel) throws IOException {
            // 修改数据
            UpdateRequest request = new UpdateRequest();
            request.index(EsConstant.CONTENT_INDEX).id(contentModel.getContentId().toString());
            String s = JSON.toJSONString(contentModel);
            request.doc(s, XContentType.JSON);
    
            UpdateResponse updateResponse = restHighLevelClient.update(request, EsConfig.COMMON_OPTIONS);
            if (updateResponse.status().getStatus()== RestStatus.OK.getStatus()){
                return true;
            }
            return false;
        }
    
    
    
    
    }

    使用直接注入 EsService 然后调用里面的方法即可

    由于每种业务查询的写法都不一定,没有通用性  所以这里没有提供查询的方法

    -----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------ (蓝奏云官网有些地址失效了,需要把请求地址lanzous改成lanzoux才可以)
  • 相关阅读:
    IO 单个文件的多线程拷贝
    day30 进程 同步 异步 阻塞 非阻塞 并发 并行 创建进程 守护进程 僵尸进程与孤儿进程 互斥锁
    day31 进程间通讯,线程
    d29天 上传电影练习 UDP使用 ScketServer模块
    d28 scoket套接字 struct模块
    d27网络编程
    d24 反射,元类
    d23 多态,oop中常用的内置函数 类中常用内置函数
    d22 封装 property装饰器 接口 抽象类 鸭子类型
    d21天 继承
  • 原文地址:https://www.cnblogs.com/pxblog/p/14808454.html
Copyright © 2011-2022 走看看