当前位置: 首页 > article >正文

SpringBoot ElasticSearch 【SpringBoot系列16】

SpringCloud 大型系列课程正在制作中,欢迎大家关注与提意见。
程序员每天的CV 与 板砖,也要知其所以然,本系列课程可以帮助初学者学习 SpringBooot 项目开发 与 SpringCloud 微服务系列项目开发

elasticsearch是一款非常强大的开源搜索引擎,具备非常多强大功能,可以帮助我们从海量数据中快速找到需要的内容。
本项目数据库使用的是 MySql ,查询数据使用的是 ElasticSearch

在这里插入图片描述

1 项目准备

SpringBoot RabbitMQ 延时队列取消订单【SpringBoot系列14】 本文章 基于这个项目来开发

本文章是系列文章 ,每节文章都有对应的代码,每节的源码都是在上一节的基础上配置而来,对应的视频讲解课程正在火速录制中。

1 项目依赖添加

首先是你的开发环境 以及服务器要安装es,我这里是使用 docker 来安装的 docker-compose安装elasticsearch及kibana

项目 pom.xm 中添加依赖

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <!--测试使用-->
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.13.2</version>
         <scope>test</scope>
     </dependency>

application.yml 中添加 es 的连接地址

elasticsearch:
  host: 127.0.0.1
  port: 9200

2 索引管理 - 相当数据库中的表

索引就像是数据库或者数据库中的表,我们平时是不会是通过java代码频繁的去创建修改删除数据库或者表的相关信息,我们只会针对数据做CRUD的操作。
kibana 提供了便捷的控制台开发工具
在这里插入图片描述
所以在使用 ElasticSearch 时,需要先使用 控制台来创建索引库,就好比你在操作数据库时,要先创建数据库与表 .

索引(Index),就是相同类型的文档的集合。
例如:

  • 所有用户文档,就可以组织在一起,称为用户的索引;
  • 所有商品的文档,可以组织在一起,称为商品的索引;
  • 所有订单的文档,可以组织在一起,称为订单的索引;
    在这里插入图片描述
    因此,我们可以把索引当做是数据库中的表。
2.1 mysql与elasticsearch

在这里插入图片描述

2.2 创建索引库

如本项目要将订单数据保存到ES中,所以这里要创建订单的索引库,创建索引库和映射的基本语法如下

PUT /order
{
  "mappings": {
    "properties": {
      "id": {
        "type": "long"
      },
      "userId": {
        "type": "long"
      },
      "goodsId": {
        "type": "long"
      },
      "deliveryAddrId": {
        "type": "integer"
      },
      "sn": {
        "type": "long"
      },
      "goodsName": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "goodsPrice": {
        "type": "double"
      },
      "goodsCount": {
        "type": "integer"
      },
      "orderChannel": {
        "type": "integer"
      },
      "status": {
        "type": "integer"
      },
      "payDate": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss"
      },
      "createDate": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss"
      }
    }
  }
}
  • type:字段数据类型,常见的简单类型有:
    • 字符串:text(可分词的文本)、keyword(精确值,例如:品牌、国家、ip地址)
    • 数值:long、integer、short、byte、double、float、
    • 布尔:boolean
    • 日期:date
    • 对象:object
  • index:是否创建索引,默认为true
  • analyzer:使用哪种分词器
  • properties:该字段的子字段

在这里插入图片描述
然后查询一下索引库

#查询
GET /order

在这里插入图片描述
删除索引库

#删除
DELETE /order

3 文档操作

这是现在数据库中订单表的数据
在这里插入图片描述

3.1 保存一条数据
import com.alibaba.fastjson.JSON;
import com.biglead.demo.pojo.Order;
import com.biglead.demo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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


@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class ESDocumentTests {

    @Resource
    RestHighLevelClient restHighLevelClient;
    @Resource
    OrderService orderService;

    /**
     * 增加文档信息
     */
    @Test
    public void addDocument() throws IOException {

        // 查询订单信息
        Order order = orderService.getOrderDetail(83L);

        // 将对象转为json
        String data = JSON.toJSONString(order);
        // 创建索引请求对象
        // 参数一 索引库名  参数二文档名称
        IndexRequest indexRequest = new IndexRequest("order").id(order.getId() + "");
        // 准备JSON文档
        indexRequest.source(data, XContentType.JSON);
        // 执行增加文档
        IndexResponse response = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        log.info("创建状态:{}", response.status());
    }

}

我这里直接将 Order 实体的数据同步到了 ES中,这就要求对数据类型以及字段的完全匹配

@TableName("t_order")
@Data
public class Order implements Serializable {

    private static final long serialVersionUID = 1L;

    /** 订单ID **/
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /** 用户ID **/
    private Long userId;
    /** 商品订单号 **/
    private Long sn;

    /** 商品ID **/
    private Long goodsId;

    /** 收获地址ID **/
    private Long deliveryAddrId;

    /** 商品名字 **/
    private String goodsName;

    /** 商品数量 **/
    private Integer goodsCount;

    /** 商品价格 **/
    private BigDecimal goodsPrice;

    /** 1 pc,2 android, 3 ios **/
    private Integer orderChannel;

    /** 订单状态,0 新建未支付,1已支付,2已发货,3已收货,4已退货,5已完成 ,6已取消**/
    private Integer status;

    /** 订单创建时间 **/
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createDate;

    /** 支付时间 **/
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date payDate;

}

比如我这里的 Order 的 id 是 long 类型,如果ES 中对应的id 字段长度我定义为 integer 类型,同步时就会出错,因为长度不一样

在这里插入图片描述

3.2 查询上述数据
    /**
     * 获取文档信息
     */
    @Test
    public void getDocument() throws IOException {
        // 创建获取请求对象
        GetRequest getRequest = new GetRequest("order", "83");
        GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
    }

在这里插入图片描述

3.3 修改

    /**
     * 更新文档信息
     */
    @Test
    public void updateDocument() throws IOException {

        // 设置商品更新信息
        Order goods = new Order();
        goods.setGoodsName("Apple iPhone 苹果手机");
        goods.setGoodsPrice(new BigDecimal("345"));

        // 将对象转为json
        String data = JSON.toJSONString(goods);
        // 创建索引请求对象
        UpdateRequest updateRequest = new UpdateRequest("order", "83");
        // 设置更新文档内容
        updateRequest.doc(data, XContentType.JSON);
        // 执行更新文档
        UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        log.info("创建状态:{}", response.status());
    }

3.4 删除

    /**
     * 删除文档信息
     */
    @Test
    public void deleteDocument() throws IOException {

        // 创建删除请求对象
        DeleteRequest deleteRequest = new DeleteRequest("order", "1");
        // 执行删除文档
        DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        log.info("删除状态:{}", response.status());
    }

3.5 批量插入数据
    @Test
   public void testBulkRequest() throws IOException {
        // 批量查询订单数据
        List<Order> orderList = orderService.alllist();

        // 1.创建Request
        BulkRequest request = new BulkRequest();
        // 2.准备参数,添加多个新增的Request
        for (Order order : orderList) {
            // 创建新增文档的Request对象
            request.add(new IndexRequest("order")
                    .id(order.getId().toString())
                    .source(JSON.toJSONString(order), XContentType.JSON));
        }
        // 3.发送请求
        BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        log.info("执行状态:{}", bulk.status());
    }

在这里插入图片描述

项目源码在这里 :https://gitee.com/android.long/spring-boot-study/tree/master/biglead-api-12-es
有兴趣可以关注一下公众号:biglead


  1. 创建SpringBoot基础项目
  2. SpringBoot项目集成mybatis
  3. SpringBoot 集成 Druid 数据源【SpringBoot系列3】
  4. SpringBoot MyBatis 实现分页查询数据【SpringBoot系列4】
  5. SpringBoot MyBatis-Plus 集成 【SpringBoot系列5】
  6. SpringBoot mybatis-plus-generator 代码生成器 【SpringBoot系列6】
  7. SpringBoot MyBatis-Plus 分页查询 【SpringBoot系列7】
  8. SpringBoot 集成Redis缓存 以及实现基本的数据缓存【SpringBoot系列8】
  9. SpringBoot 整合 Spring Security 实现安全认证【SpringBoot系列9】
  10. SpringBoot Security认证 Redis缓存用户信息【SpringBoot系列10】
  11. SpringBoot 整合 RabbitMQ 消息队列【SpringBoot系列11】
  12. SpringBoot 结合RabbitMQ与Redis实现商品的并发下单【SpringBoot系列12】
  13. SpringBoot 雪花算法生成商品订单号【SpringBoot系列13】
  14. SpringBoot RabbitMQ 延时队列取消订单【SpringBoot系列14】
  15. SpringBoot RabbitMQ 商品秒杀【SpringBoot系列15】

http://www.kler.cn/news/10515.html

相关文章:

  • 归排、计排深度理解
  • docker运行服务端性能监控系统Prometheus和数据分析系统Grafana
  • 智慧校园大数据云平台(4)
  • 2023.04.16 学习周报
  • Java学习
  • 【数据结构】解析队列各接口功能实现
  • JS实用技巧断点调试详解
  • 一、docker-技术架构
  • C++ Primer阅读笔记--标准库类型string和vector的使用
  • oracle中sql 正则怎么写?
  • ArrayList的深入理解
  • 不会注册ChatGPT?4个国内网站让你尽情体验
  • GameFramework 框架详解之 如何接入热更框架HybridCLR
  • 【音频处理】创建环绕声混响
  • pycharm笔记
  • 内部人员或给企业造成毁灭性损失
  • LAZADA将缩短履约时效,卖家发货倍感压力
  • 代码随想录_226翻转二叉树、101对称二叉树
  • item_search_img-按图搜索1688商品(拍立淘)接口的接入参数说明
  • 跟着AI学AI(2): 逻辑回归
  • Spring Cloud快速入门
  • 网络安全之入侵检测
  • NVIDIA- cuSPARSE(四)
  • 【Flutter进阶】聊一聊组件中的生命周期、状态管理及局部重绘
  • 数据优化 | CnOpenDataA股上市公司招聘数据
  • 关于合金电阻
  • vue项目用后端返回的文件流实现docx和pdf文件预览
  • Java 进阶(11) 线程安全
  • virtualbox如何配网
  • 含有分布式电源的三相不平衡配电网潮流计算【IEEE33节点】(Matlab代码实现)