SpringBoot集成Elasticsearch7.12.1实现增删改查代码---干货

项目依赖:

<!-- ElasticSearch依赖 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.12.1</version>
        </dependency>

配置类:

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

@Slf4j
@Configuration
public class EsConfig {
    private RestHighLevelClient client;

    //注入IOC容器
    @Bean
    public RestHighLevelClient esClient() {
        RestClientBuilder builder = RestClient.builder(HttpHost.create("http://es地址:9200"));
        client = new RestHighLevelClient(builder);
        return client;
    }

    @PreDestroy
    public void closeEsClient() {
        try {
            this.client.close();
        } catch (IOException e) {
            log.error("es close错误: {}", e.getMessage());
        }
    }

}

常量配置:

public class EsConstants {
    //索引名
    public static final String INDEX_NAME = "bladex_goods";
    
     /**
     * 此模板相当于数据库中建表结构
     * type:数据类型,字符串:text(可分词的文本)、keyword(精确值,不可分词,例如:品牌、国家等)
     * 每个字段默认自带 index=true,意思是创建倒排索引,可以被搜索
     * analyzer:表示分词,和text结合使用
     * copy_to:表示字段拷贝,将当前字段拷贝到指定字段  在页面中支持输入一个参数,可以搜索es中多个字段
     */
    public static final String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"saleStore\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"title\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"buyPrice\": {\n" +
            "        \"type\": \"double\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"salePrice\": {\n" +
            "        \"type\": \"double\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"saleDate\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"all\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}

向es中存数据实体类:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class EsGoodsIndex implements Serializable {
    //阿里订单号
    private String id;
    //卖出店铺
    private String saleStore;
    //商品标题
    private String title;
    //买入价格
    private Double buyPrice;
    //卖出价格
    private Double salePrice;
    //卖出时间
    private String saleDate;
}

封装抽象类,实现业务需继承此类:

import com.alibaba.fastjson.JSON;
import com.bladex.common.core.es.constant.EsConstants;
import com.bladex.common.core.es.enity.EsGoodsIndex;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
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.xcontent.XContentType;

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

//es基础类
@Slf4j
public abstract class BaseEsService {
    @Resource
    public RestHighLevelClient client;

    //判断索引是否存在
    protected Boolean existsIndex() {
        try {
            return client.indices().exists(new GetIndexRequest(EsConstants.INDEX_NAME), RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("判断索引是否存在失败:{}", e.getMessage());
        }
        return false;
    }

    //创建索引库
    protected Boolean createIndex() {
        //查询索引是否存在
        try {
            boolean exists = this.existsIndex();
            if (!exists) {
                //不存在,则创建
                CreateIndexRequest request = new CreateIndexRequest(EsConstants.INDEX_NAME);
                request.source(EsConstants.MAPPING_TEMPLATE, XContentType.JSON);
                CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
                return response.isAcknowledged();
            }
        } catch (IOException e) {
            log.error("创建索引失败:{}", e.getMessage());
        }
        return true;
    }

    //向es新增数据
    protected void insertEs(EsGoodsIndex index) {
        try {
            client.index(new IndexRequest(EsConstants.INDEX_NAME)
                            .id(index.getId())
                            .source(JSON.toJSONString(index),XContentType.JSON),
                    RequestOptions.DEFAULT);
            log.info("保存es数据成功!");
        } catch (IOException e) {
            log.error("向es新增数据失败:{}", e.getMessage());
        }
    }

    //向es批量新增数据
    protected void bulkInsert(List<EsGoodsIndex> indexList) {
        try {
            BulkRequest request = new BulkRequest();
            indexList.forEach(r -> {
                request.add(new IndexRequest(EsConstants.INDEX_NAME).id(r.getId()).source(JSON.toJSONString(r), XContentType.JSON));
            });
            client.bulk(request, RequestOptions.DEFAULT);
            log.info("批量保存es数据成功!");
        } catch (IOException e) {
            log.error("向es批量新增数据失败:{}", e.getMessage());
        }
    }

    //修改es数据
    protected void updateEs(EsGoodsIndex index) {
        try {
            client.update(new UpdateRequest(EsConstants.INDEX_NAME, index.getId())
                            .doc("buyPrice", index.getBuyPrice(), "salePrice", index.getSalePrice()),
                    RequestOptions.DEFAULT);
            log.info("修改es数据成功!");
        } catch (IOException e) {
            log.error("修改es数据失败:{}", e.getMessage());
        }
    }

    //删除es数据
    protected void deleteEs(String id) {
        try {
            client.delete(new DeleteRequest(EsConstants.INDEX_NAME, id), RequestOptions.DEFAULT);
            log.info("删除es数据成功!");
        } catch (IOException e) {
            log.error("删除es数据失败:{}", e.getMessage());
        }
    }

}

//查询接口待更新

备注:所有接口均测试

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值