Elasticsearch8.1-ElasticsearchClient-Java客户端简单增删查改-随笔

  1. 环境准备
    1. Springboot 基本环境
      1. 自行前往//start.spring.io/ 构建一个即可
    2. Elasticsearch服务端
      1. 简单说下windows版本的安装  //www.elastic.co/cn/downloads/elasticsearch   下载最新版8.1.0,之后解压 不要放到中文目录下,进入bin目录双击运行elasticsearch.bat.
  2. 相关依赖
    1. pom.xml   ELasticsearch相关的依赖

      <dependency>
          <groupId>co.elastic.clients</groupId>
          <artifactId>elasticsearch-java</artifactId>
          <version>8.1.0</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.13.2</version>
      </dependency>
    2. application.yml
      elasticsearch:
        host: 127.0.0.1
        port: 9200
  3. 代码逻辑解释
    1. 创建Elasticsearch 客户端 的bean 对象
      查看代码
      package cn.daimao.TestTryProject.bean;
      import co.elastic.clients.elasticsearch.ElasticsearchClient;
      import co.elastic.clients.json.jackson.JacksonJsonpMapper;
      import co.elastic.clients.transport.ElasticsearchTransport;
      import co.elastic.clients.transport.rest_client.RestClientTransport;
      import org.apache.http.HttpHost;
      import org.elasticsearch.client.RestClient;
      import org.elasticsearch.client.RestClientBuilder;
      import org.springframework.beans.factory.annotation.Value;
      import org.springframework.context.annotation.Bean;
      import org.springframework.stereotype.Component;
      @Component
      public class ElasticClient {
          @Value("${elasticsearch.host}")
          private String host;
          @Value("${elasticsearch.port}")
          private Integer port;
          @Bean
          public ElasticsearchClient getClient(){
              RestClientBuilder builder = RestClient.builder(
                      new HttpHost(host, port));
              ElasticsearchTransport transport = new RestClientTransport(builder.build(),new JacksonJsonpMapper());
              return new ElasticsearchClient(transport);
          }
      }
      

       

    2. 准备测试对象
      1. 创建测试商品表
        SET NAMES utf8mb4;
        SET FOREIGN_KEY_CHECKS = 0;
        
        -- ----------------------------
        -- Table structure for t_product
        -- ----------------------------
        DROP TABLE IF EXISTS `t_product`;
        CREATE TABLE `t_product`  (
          `product_id` bigint(0) NOT NULL AUTO_INCREMENT,
          `product_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品名称',
          `product_price` decimal(10, 2) NULL DEFAULT NULL COMMENT '商品价格',
          `product_category` bigint(0) NULL DEFAULT NULL COMMENT '商品分类',
          `product_imgurl` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品图片地址',
          `product_num` int(0) NULL DEFAULT NULL COMMENT '商品库存',
          `product_description` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商品简单描述',
          `sale` bigint(0) NULL DEFAULT NULL COMMENT '销量',
          `quill` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '详细描述',
          `product_status` int(0) NULL DEFAULT NULL COMMENT '状态',
          `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
          `create_id` bigint(0) NULL DEFAULT NULL COMMENT '创建人',
          PRIMARY KEY (`product_id`) USING BTREE
        ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
        
        SET FOREIGN_KEY_CHECKS = 1;

        2.使用mybatis-plus 生成商品相应对象、service、mapper等

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        查看代码
        package cn.daimao.TestTryProject.domain;
        
        import com.baomidou.mybatisplus.annotation.IdType;
        import com.baomidou.mybatisplus.annotation.TableField;
        import com.baomidou.mybatisplus.annotation.TableId;
        import com.baomidou.mybatisplus.annotation.TableName;
        import java.io.Serializable;
        import java.math.BigDecimal;
        import java.util.Date;
        import lombok.Data;
        
        /**
         * 
         * @TableName t_product
         */
        @TableName(value ="t_product")
        @Data
        public class TProduct implements Serializable {
            /**
             * 
             */
            @TableId(type = IdType.AUTO)
            private Long productId;
        
            /**
             * 商品名称
             */
            private String productName;
        
            /**
             * 商品价格
             */
            private BigDecimal productPrice;
        
            /**
             * 商品分类
             */
            private Long productCategory;
        
            /**
             * 商品图片地址
             */
            private String productImgurl;
        
            /**
             * 商品库存
             */
            private Integer productNum;
        
            /**
             * 商品简单描述
             */
            private String productDescription;
        
            /**
             * 销量
             */
            private Long sale;
        
            /**
             * 详细描述
             */
            private String quill;
        
            /**
             * 状态
             */
            private Integer productStatus;
        
            /**
             * 创建时间
             */
            private Date createTime;
        
            /**
             * 创建人
             */
            private Long createId;
        
            @TableField(exist = false)
            private static final long serialVersionUID = 1L;
        
            @Override
            public boolean equals(Object that) {
                if (this == that) {
                    return true;
                }
                if (that == null) {
                    return false;
                }
                if (getClass() != that.getClass()) {
                    return false;
                }
                TProduct other = (TProduct) that;
                return (this.getProductId() == null ? other.getProductId() == null : this.getProductId().equals(other.getProductId()))
                    && (this.getProductName() == null ? other.getProductName() == null : this.getProductName().equals(other.getProductName()))
                    && (this.getProductPrice() == null ? other.getProductPrice() == null : this.getProductPrice().equals(other.getProductPrice()))
                    && (this.getProductCategory() == null ? other.getProductCategory() == null : this.getProductCategory().equals(other.getProductCategory()))
                    && (this.getProductImgurl() == null ? other.getProductImgurl() == null : this.getProductImgurl().equals(other.getProductImgurl()))
                    && (this.getProductNum() == null ? other.getProductNum() == null : this.getProductNum().equals(other.getProductNum()))
                    && (this.getProductDescription() == null ? other.getProductDescription() == null : this.getProductDescription().equals(other.getProductDescription()))
                    && (this.getSale() == null ? other.getSale() == null : this.getSale().equals(other.getSale()))
                    && (this.getQuill() == null ? other.getQuill() == null : this.getQuill().equals(other.getQuill()))
                    && (this.getProductStatus() == null ? other.getProductStatus() == null : this.getProductStatus().equals(other.getProductStatus()))
                    && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()))
                    && (this.getCreateId() == null ? other.getCreateId() == null : this.getCreateId().equals(other.getCreateId()));
            }
        
            @Override
            public int hashCode() {
                final int prime = 31;
                int result = 1;
                result = prime * result + ((getProductId() == null) ? 0 : getProductId().hashCode());
                result = prime * result + ((getProductName() == null) ? 0 : getProductName().hashCode());
                result = prime * result + ((getProductPrice() == null) ? 0 : getProductPrice().hashCode());
                result = prime * result + ((getProductCategory() == null) ? 0 : getProductCategory().hashCode());
                result = prime * result + ((getProductImgurl() == null) ? 0 : getProductImgurl().hashCode());
                result = prime * result + ((getProductNum() == null) ? 0 : getProductNum().hashCode());
                result = prime * result + ((getProductDescription() == null) ? 0 : getProductDescription().hashCode());
                result = prime * result + ((getSale() == null) ? 0 : getSale().hashCode());
                result = prime * result + ((getQuill() == null) ? 0 : getQuill().hashCode());
                result = prime * result + ((getProductStatus() == null) ? 0 : getProductStatus().hashCode());
                result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode());
                result = prime * result + ((getCreateId() == null) ? 0 : getCreateId().hashCode());
                return result;
            }
        
            @Override
            public String toString() {
                StringBuilder sb = new StringBuilder();
                sb.append(getClass().getSimpleName());
                sb.append(" [");
                sb.append("Hash = ").append(hashCode());
                sb.append(", productId=").append(productId);
                sb.append(", productName=").append(productName);
                sb.append(", productPrice=").append(productPrice);
                sb.append(", productCategory=").append(productCategory);
                sb.append(", productImgurl=").append(productImgurl);
                sb.append(", productNum=").append(productNum);
                sb.append(", productDescription=").append(productDescription);
                sb.append(", sale=").append(sale);
                sb.append(", quill=").append(quill);
                sb.append(", productStatus=").append(productStatus);
                sb.append(", createTime=").append(createTime);
                sb.append(", createId=").append(createId);
                sb.append(", serialVersionUID=").append(serialVersionUID);
                sb.append("]");
                return sb.toString();
            }
        }
        查看代码
        package cn.daimao.TestTryProject.service;
        
        import cn.daimao.TestTryProject.domain.TProduct;
        import com.baomidou.mybatisplus.extension.service.IService;
        
        /**
        * @author 毛明辉
        * @description 针对表【t_product】的数据库操作Service
        * @createDate 2022-04-06 14:40:35
        */
        public interface TProductService extends IService<TProduct> {
        
        }
        
        package cn.daimao.TestTryProject.service.impl;
        
        import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
        import cn.daimao.TestTryProject.domain.TProduct;
        import cn.daimao.TestTryProject.service.TProductService;
        import cn.daimao.TestTryProject.mapper.TProductMapper;
        import org.springframework.stereotype.Service;
        
        /**
        * @author 毛明辉
        * @description 针对表【t_product】的数据库操作Service实现
        * @createDate 2022-04-06 14:40:35
        */
        @Service
        public class TProductServiceImpl extends ServiceImpl<TProductMapper, TProduct>
            implements TProductService{
        
        }
        
        
        
        
        
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "//mybatis.org/dtd/mybatis-3-mapper.dtd">
        <mapper namespace="cn.daimao.TestTryProject.mapper.TProductMapper">
        
            <resultMap id="BaseResultMap" type="cn.daimao.TestTryProject.domain.TProduct">
                    <id property="productId" column="product_id" jdbcType="BIGINT"/>
                    <result property="productName" column="product_name" jdbcType="VARCHAR"/>
                    <result property="productPrice" column="product_price" jdbcType="DECIMAL"/>
                    <result property="productCategory" column="product_category" jdbcType="BIGINT"/>
                    <result property="productImgurl" column="product_imgurl" jdbcType="VARCHAR"/>
                    <result property="productNum" column="product_num" jdbcType="INTEGER"/>
                    <result property="productDescription" column="product_description" jdbcType="VARCHAR"/>
                    <result property="sale" column="sale" jdbcType="BIGINT"/>
                    <result property="quill" column="quill" jdbcType="VARCHAR"/>
                    <result property="productStatus" column="product_status" jdbcType="INTEGER"/>
                    <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
                    <result property="createId" column="create_id" jdbcType="BIGINT"/>
            </resultMap>
        
            <sql id="Base_Column_List">
                product_id,product_name,product_price,
                product_category,product_imgurl,product_num,
                product_description,sale,quill,
                product_status,create_time,create_id
            </sql>
        </mapper>
        

         

      2. Elasticsearch相关
        1. 创建索引product,可以手动创建,客户端API方法如下,indexName传product即可,简单创建一下就行。
          @Autowired
          private ElasticsearchClient elasticsearchClient;
          @PostMapping("/createIndex")
          public ResultJson createIndex(@RequestParam String indexName) throws IOException {
              elasticsearchClient.indices().create(createIndex -> createIndex.index(indexName));
              return ResultJson.success();
          }

           

        2. product 增删改  直接上代码 ,毕竟简单
          package cn.daimao.TestTryProject.service;
          
          import cn.daimao.TestTryProject.common.ResultJson;
          import cn.daimao.TestTryProject.domain.TProduct;
          import co.elastic.clients.elasticsearch.ElasticsearchClient;
          import co.elastic.clients.elasticsearch.core.DeleteRequest;
          import co.elastic.clients.elasticsearch.core.IndexRequest;
          import co.elastic.clients.elasticsearch.core.UpdateRequest;
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.stereotype.Service;
          
          import java.io.IOException;
          
          @Service
          public class ElasticSearchService {
              @Autowired
              private ElasticsearchClient elasticsearchClient;
          
              /**
               * 上传商品相关数据到Elasticsearch
               * @param tProduct
               */
              public ResultJson uploadProduct(TProduct tProduct)  {
                  IndexRequest<TProduct> req ;
                  req = IndexRequest.of( b->
                          b.index("product").id(tProduct.getProductId()+"").document(tProduct));
                  try {
                      elasticsearchClient.index(req);
                      return ResultJson.success();
                  } catch (IOException e) {
                      return ResultJson.failure(e.toString());
                  }
              }
          
              /**
               * 修改
               * @param tProduct
               * @return
               */
              public ResultJson updateDocument(TProduct tProduct){
                  UpdateRequest<TProduct,TProduct> req;
                  req = UpdateRequest.of(
                          b-> b.index("product").id(tProduct.getProductId()+"")
                                          .doc(tProduct)
                  );
                  try {
                      elasticsearchClient.update(req,TProduct.class);
                      return ResultJson.success();
                  } catch (IOException e) {
                      return ResultJson.failure(e.toString());
                  }
              }
          
              /**
               * 删除
               * @param productId
               * @return
               */
              public ResultJson deleteDocument(Long productId){
                  DeleteRequest req ;
                  req = DeleteRequest.of(
                          b-> b.index("product").id(productId+"")
                  );
          
                  try {
                      elasticsearchClient.delete(req);
                      return ResultJson.success();
                  } catch (IOException e) {
                      return ResultJson.failure(e.toString());
                  }
              }
          }
          

          在商品操作的时候调用一下即可

          package cn.daimao.TestTryProject.controller;
          
          import cn.daimao.TestTryProject.common.ResultJson;
          import cn.daimao.TestTryProject.domain.TProduct;
          import cn.daimao.TestTryProject.service.ElasticSearchService;
          import cn.daimao.TestTryProject.service.TProductService;
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.web.bind.annotation.*;
          
          import java.util.Date;
          
          @RestController
          @RequestMapping("/api/product")
          public class ProductController {
              @Autowired
              private TProductService tProductService;
              @Autowired
              private ElasticSearchService elasticSearchService;
          
              @PostMapping("/save")
              public ResultJson save(@RequestBody TProduct tProduct){
                  tProduct.setCreateTime(new Date());
                  tProductService.save(tProduct);
                  return elasticSearchService.uploadProduct(tProduct);
              }
              @PostMapping("/update")
              public ResultJson update(@RequestBody TProduct tProduct){
                  tProductService.updateById(tProduct);
                  return elasticSearchService.updateDocument(tProduct);
              }
              @PostMapping("/delete")
              public ResultJson delete(@RequestParam Long productId){
                  tProductService.removeById(productId);
                  return elasticSearchService.deleteDocument(productId);
              }
          
          }
          

           

          漏发了一个通用类,比较简单, 不发了。

  4. 成果展示
    1. 数据我update过,总之是已经传到Elasticsearch上面了。
  5. 查询,后面再补,这个才是关键。