• ElasticSearch (ES)学习之路(六)Springboot2.3.1整合ES 7.6.1


    ElasticSearch (ES)学习之路(六)Springboot2.3.1整合ES 7.6.1

    本文采用springboot2.3.1版本 es版本为7.6.1

    引入依赖

    maven
            
                org.springframework.boot
                spring-boot-starter-data-elasticsearch
            
    
    • 1
    • 2
    • 3
    • 4
    gardle
      plugins {
        id 'org.springframework.boot' version '2.3.1.RELEASE'
        id 'io.spring.dependency-management' version '1.0.9.RELEASE'
        id 'java'
    }
      implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    温馨提示:springboot版本中内嵌了es版本 ,如果与服务器版本不一致,需强制改动其依赖版本

    springboot2.3.1 版本中配置es 版本为7.6.2 ,由于个人服务器上版本为7.6.1 所以呢,需要强制更改一下版本

    maven 更改方法

    properties 中指定版本号

        
            7.6.1
        
    
    • 1
    • 2
    • 3

    可能有人问,为什么要这么定义es版本号前后缀?

    因为 springboot父工程就是这样定义版本号的,所以我们平时在引入依赖时无需显示申明版本号

    image-20200712173334915

    gradle更改依赖版本方法

    image-20200712173603034

        compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-high-level-client', version: '7.6.1'
    
        compile group: 'org.elasticsearch', name: 'elasticsearch', version: '7.6.1'
    
        compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-client', version: '7.6.1'
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在我们学习ES的时候,就已经讲过 ,初学期间,我们直接把 indexs 当做数据库 type当做表 document当做一行数据

    在操作mysql数据库的时候啊,我们通常会定义pojo实体类,一个类呢,对应着一个表,然后使用jpa /mybatis 对这个类做操作,然后保存到我们的数据库即可。

    那么ES是否可以定义一个实体类,然后操作到ES服务器上呢?ES 在springboot中如何使用呢?

    咱们进入今天的正题:springboot整合es

    springboot 整合es

    配置链接信息

    springboot中 连接es很简单

    uris 表明其需要连接的集群 (我这里只有一个,es ,一个人就是一支军队,一个节点也是集群)

    spring:
      elasticsearch:
        rest:
          uris: localhost:9200
    
    • 1
    • 2
    • 3
    • 4

    如果是Linux服务器上安装的话 ,可能还需要配置连接es的账户和密码

    spring:
      elasticsearch:
        rest:
          uris: localhost:9200
          password: xxx
          username: xxx
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    定义实体类

    前文已经抛砖了,我这里直接解答!

    es 在springboot中使用,同样可定义实体类 ,使其绑定到索引库以及type上,并能根据字段类型设置mapping映射.

    @Document 注解注意引用的是import org.springframework.data.elasticsearch.annotations.Document下

    在项目使用了Mongodb的时候,格外要注意这点!

    indexName指定了 索引库名

    我这里是没有写_type的, 虽然哈,一直说 将type作为表来理解,但是es 与mysql终究是不一样的,后续es 8.x会去除type操作 _type ,我这里没写,因为其默认了,

    shards 指定分片

    replicas 指定副本集 此二者无特殊场景,默认即可

    image-20200712175112568

    @Id 注意 引入的是 import org.springframework.data.annotation.Id包下的

    @Field 可指定字段类型,与es中mapping设定需要规约的类型一致,并且可选择分词器(前面已经安装了IK)

    #image-20200712174510562

    定义dao 接口继承ElasticsearchRepository

    由于本文使用的jpa 实现的es 操作,所以呢,大致和jpa 一样,按照其规范来就行

    ElasticsearchRepository 中泛型 一个是要操作的实体类,一个是实体类主键ID 类型

    image-20200712175231688

    继承了此接口 ,基础文档CRUD 接口即做好了

    咱们可以来试一试

    定义服务层 (逻辑处理)

    我这里就省略了服务层的接口,,,(哈哈,偷个懒)

    image-20200712175451837

    其继承ElasticsearchRepository 后呢,仅仅只是对文档中操作,索引库操作,不能使用他

    sprinboot中 操作es 索引库 服务层 中注入

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dk6PVTo1-1594550575037)(https://leileidev.oss-cn-chengdu.aliyuncs.com/img/image-20200712175712537.png)]

    其中 ElasticsearchRestTemplate 中提供了许许多多的方法(参考 redistemplate),基本springboot版本,可能有的过时了还是怎样,反正一切操作,都可以在其中找到(api工程师 本师)

    新建索引
        /**
         * 创建/更新索引
         */
        public boolean createOrUpdateIndex() {
            IndexOperations indexOperations = esTemplate.indexOps(Product.class);
            indexOperations.createMapping(Product.class);
            return indexOperations.create();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    判断索引是否存在
    /**
     * 判断索引是否存在
     *
     * @return
     */
    public boolean indexExists() {
        IndexOperations indexOperations = esTemplate.indexOps(Product.class);
        return indexOperations.exists();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    image-20200712183737997

    删除索引
    /**
     * 删除索引
     */
    public boolean deleteIndex() {
        IndexOperations indexOperations = esTemplate.indexOps(Product.class);
        return indexOperations.delete();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    基本上 ElasticsearchRestTemplate 操作索引库就这些方法,,,当然,他也是可以操作文档的,但是呢,本文还是采用了jpa 方式来操作(根据规范编写方法名,即可合理操作ES)

    注入我们自定义且继承ElasticsearchRepository 的即可即可 操作文档CRUD

    image-20200712180742286

    新增修改文档数据
    /**
     * 新增或者修改数据
     */
    public Product save(Product product) {
        return productRepository.save(product);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    image-20200712180411977

    修改 主键不变,改一些属性即可

    image-20200712180629462

    image-20200712180647487

    删除文档数据
    /**
     * 删除数据
     */
    public Boolean delete(Long id) {
        try {
            productRepository.deleteById(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    根据ID 查询一个
    /**
     * 根据ID 查询一个
     *
     * @param id
     * @return
     */
    public Optional getProduct(Long id) {
        return productRepository.findById(id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    jpa 中 自定义方法 查询

    自定义根据类型 查询方法 无分页

    image-20200712181851479

        public List findAllByBrand(String Brand) {
            List products = productRepository.findProductsByBrand(Brand);
            return products;
        }
    
    • 1
    • 2
    • 3
    • 4

    如果需要分页 ,则在dao接口中 添加一个一个方法参数 Pageable 即可

    image-20200712182039074

    注意点1:添加分页后,就不能返回为List了,必须返回Page<操作的实体> 对象,我们查询的结果已经帮我们封装金里边了

    注意点2:

    这个分页 我们可以使用 PageRequest.of进行构造 ,但是es 分页默认是从0页开始的,所以呢,想要查询第一页的数据则,PageRequest.of 参数要为0

    例如: 查询第一页数据,一页最多展示15条数据

    PageRequest.of(0, 15)
    
    • 1

    image-20200712182239728

    查询所有可自定义正序/倒叙排列 默认倒叙
        public Page findAll(Integer page, Integer size, String field, String order) {
            Page all = productRepository.findAll(
                    PageRequest.of(page-1, size,
                            Sort.by(!"desc".equals(order) ? Sort.Order.asc(field) : Sort.Order.desc(field))));
            return all;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    例如:查询第一页数据,一页最多展示十条数据 根据创建时间倒叙展示

    image-20200712181201555

    区间查询类似 Between a and b

    需要在无门的dao层编写方法 方法名按照jpa规范写

    image-20200712181353435

    不要慌,有提示的,根据方法名,猜也猜出来是干啥的了

    image-20200712181444768

        public Page findByIdBetween(Long id1,Long id2,Integer page, Integer size) {
            PageRequest of = PageRequest.of(page - 1, size);
            Page all = productRepository.findProductsByIdBetween(id1, id2,of);
            return all;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    image-20200712181737853

    search 查询
    /**
     * 根据类型查询 且分页
     */
    public Page findAllByBrandPage(String brand, Integer page, Integer size) {
        NativeSearchQuery build = new NativeSearchQueryBuilder()
                //必须匹配
                .withQuery(QueryBuilders.matchQuery("brand", brand))
                //分页
                .withPageable(PageRequest.of(page - 1, size))
                //我根据ID倒叙排列
                .withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC))
                .build();
        return productRepository.search(build);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    image-20200712182641103

    高亮查询–还有点问题

    springboot2.3.x 高亮 个人目前还有点问题,没有解决,后续更新吧

    附上项目源码:springboot2.3.1整合es 7.6.1

  • 相关阅读:
    2023年中职“网络安全“—Web 渗透测试①
    【Vue2.x源码系列02】模版编译(AST、Optimize 、Render)
    【手把手带你学JavaSE】第二篇:Java的main函数、数据类型
    Offer刷题——1
    基于微信小程序云开(统计学生信息并导出excel)
    【一花一世界-郑一教授-繁简之道】可解释神经网络
    【前端素材】推荐优质后台管理系统网页Star admin平台模板(附源码)
    SpringCloud微服务(六)——Gateway路由网关
    uniapp音频加进度条加蓝牙ibecon设备搜索
    23种设计模式(十五)解释器模式(阁瑞钛伦特软件-九耶实训)
  • 原文地址:https://blog.csdn.net/m0_67403272/article/details/126659081