代码编织梦想

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】
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zl18603543572/article/details/129626954

【SpringBoot深入浅出系列】SpringBoot之集成Elasticsearch-爱代码爱编程

目录 一、前言二、Elasticsearch 是什么?三、Elasticsearch 安装四、SpringBoot 集成 Elasticsearch 的方式1.TransportClient2.Java REST Client3.Java API Client4.Spring Data Elasticsearch五、创建项目集成 Elasticse

springboot整合elasticsearch-crud+分页查询_叫我三胖哥哥的博客-爱代码爱编程

文章目录 1. 环境配置2. 代码编写2.1 Dao层2.2 Service层2.2 Controller层3. 测试结果 ES-docker安装参考这篇: Centos7使用Docker部署Elasticsearch服务+IK分词器及Head插件安装 ES-windows安装参考这篇: windows10安装ElasticSearch与Hea

springboot simple (13) springboot elasticsearch(elasticsearch8.5.1)-爱代码爱编程

这里首先简单的介绍了Elasticsearch,然后实现了springboot集成Elasticsearch。 版本: Elasticsearch:v8.5.1 Kibana:v8.5.1 springboot集成ela