ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringBoot 整合es(elasticsearch)使用elasticsearch-rest-high-level-client实现增删改

2021-05-25 14:05:07  阅读:164  来源: 互联网

标签:return SpringBoot level new elasticsearch org import public


 

引入依赖

 <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 然后调用里面的方法即可

 

 

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

 

标签:return,SpringBoot,level,new,elasticsearch,org,import,public
来源: https://www.cnblogs.com/pxblog/p/14808454.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有