SpringBoot集成elasticsearch使用(增删改查)

news2025/3/1 2:20:26

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

SpringBoot集成elasticsearch使用(增删改查)

  • 一、es是什么?
  • 二、使用步骤
    • 1.搭配环境
  • springboot集成es
    • 1、新建springboot项目,引入相关版本依赖
    • 2.配置es.ym
    • 3. 在你的数据库实体类里每个字段加上相应的注解即可
    • 4. 操作es
    • 5.swagger +postman 测试
    • 这里只测试了添加 其余自己测 ![在这里插入图片描述](https://img-blog.csdnimg.cn/eae2a584a66c42d7a4f39647f4321764.png) ![在这里插入图片描述](https://img-blog.csdnimg.cn/4c172a8807e541c79f90a077e7eac295.png)
  • 总结
    • 1. NodeAvailableException[None of the configured nodes are availabl
      • 配置文件正确写法:
    • 2.批量删除自定义方法


一、es是什么?

Elasticsearch 是一个实时的分布式存储、搜索、分析的引擎。(全文引擎)

二、使用步骤

1.搭配环境

系统:windows 10
elasticsearch官网下载地址链接:
下载好对应的windows版本,解压到任意工作目录,es的安装非常方便,解压即用。
在这里插入图片描述
刚下载的es默认的分词器只能分解英文,对于中文不太友好。所以我们需要为es下载安装IK分词器

IK分词器下载链接:

Ik分词器下载地址,分词器下载跟es版本对应的就行。下载好后解压zip包
在这里插入图片描述

在你下载的es安装路径下的plugins文件夹下创建一个ik的文件夹,然后将上面解压出来的分词器内容复制到创建的ik文件夹下面。下面图ik分词器官方安装说明
在这里插入图片描述

ik分词器的安装就完成了,而后回答es根目录下的bin目录里,双击启动es
在这里插入图片描述

当es正常启动,且启动过程出现下面情况时,说明ik分词器已经正常安装好可以使用了
在这里插入图片描述

springboot集成es

1、新建springboot项目,引入相关版本依赖

在这里插入图片描述

这里用的elasticsearch 6.8 版本 导入

	    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
	    </parent>

      <!--springboot帮我们自动集成了es,所以只需要引入下面这一个依赖即可-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>


2.配置es.ym

server:
  port: 9007
spring:
  data:
    elasticsearch:
      cluster-name: my-application
      cluster-nodes: 127.0.0.1:9300


3. 在你的数据库实体类里每个字段加上相应的注解即可

@Document(indexName = "shop")
@Data
public class Goods  {
    /**
     * 商品id
     */
    @Field(type = FieldType.Integer)//type表示存到es当中的数据类型
    private Integer id;

    /**
     * 商品名字
     */
    @Field(type = FieldType.Text,analyzer = "ik-max-word")
    private String productName;

    /**
     * 商品描述
     */
    @Field(type = FieldType.Text,analyzer = "ik-max-word")
    private String productDescription;

    /**
     * 商品价格
     */
    @Field(type = FieldType.Double)
    private Double productPrice;

    /**
     * 商品分类id
     */
    @Field(type = FieldType.Integer)
    private Integer categoryId;

    /**
     * 商品图片
     */
    @Field(type = FieldType.Text)
    private String productImage;

    /**
     * 商品创建时间
     */
    @Field(type = FieldType.Date,format = DateFormat.basic_date_time)
    private Date productCreateTime;

    /**
     * 商品修改时间
     */
    @Field(type = FieldType.Date,format = DateFormat.basic_date_time)
    private Date productUpdateTime;

    /**
     * 商品状态(0:在销售,1:售空,2:下架)
     */
    @Field(type = FieldType.Date,format = DateFormat.basic_date_time)
    private String productStatus;

}


4. 操作es

由于spring官方对es的高度封装,我们已经可以做到像操作数据库一样操作es了

package org.springframework.data.elasticsearch.repository;

import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.lang.Nullable;

@NoRepositoryBean
public interface ElasticsearchRepository<T, ID> extends PagingAndSortingRepository<T, ID> {
    /** @deprecated */
    @Deprecated
    default <S extends T> S index(S entity) {
        return this.save(entity);
    }

    /** @deprecated */
    @Deprecated
    <S extends T> S indexWithoutRefresh(S entity);

    /** @deprecated */
    @Deprecated
    Iterable<T> search(QueryBuilder query);

    /** @deprecated */
    @Deprecated
    Page<T> search(QueryBuilder query, Pageable pageable);

    /** @deprecated */
    Page<T> search(Query searchQuery);

    Page<T> searchSimilar(T entity, @Nullable String[] fields, Pageable pageable);

    /** @deprecated */
    @Deprecated
    void refresh();
}

以上面的Goods对象举例,创建接口EsGoodsRepository,继承Spring封装的ElasticsearchRepository,ElasticsearchRepository提供了一些简单的操作es方法

创建EsGoodsRepository接口:

package com.buba.service;


import com.buba.pojo.Goods;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface EsGoodsRepository extends ElasticsearchRepository<Goods,Integer> {
}

保存或者更新时,先存db后操作es(增删改查+批量删除)。.


@RequestMapping("/goods")
@RestController
public class GoodsControoler{
    @Autowired
    private GoodService goodService;
    @Autowired
    private EsGoodsRepository esGoodsRepository;

    @Autowired
    private EsGoodsService esGoodsService;

    @PostMapping("/add")
    @ApiOperation(value = "添加商品")
    public Result<Goods> save(@RequestBody Goods goods)  {
        goods.setProductCreateTime(new Date());

        int i = goodService.insert(goods);
        if (i==1){
            // 调用EsGoodsRepository save 方法
            Goods save=esGoodsRepository.save(goods);
            return new Result(true, StatusCode.OK,"添加成功");
        }else {
            return new Result(true, StatusCode.ERROR,"添加失败");
        }

    }

//     引用pagehelper写分页查询
    @GetMapping("/list")
    @ApiOperation(value = "查询商品列表")
    public Result list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {

        PageInfo<Goods> page = goodService.findAllUserByPageS(pageNum,pageSize);
        return new Result(true, StatusCode.OK, "查询成功", page);
    }

    @GetMapping("/searchGoods")
    @ApiOperation(value = "查询检索功能")
    public Result searchProduct(@RequestParam("productName") String productName,@RequestParam(value = "pageNum", defaultValue = "0") int pageNum, @RequestParam(value = "pageSize", defaultValue = "1") int pageSize){
        QueryBuilder  queryBuilder  = QueryBuilders.matchQuery("productName", productName);
        PageRequest pageRequest  = PageRequest.of(pageNum, pageSize);

        Page<Goods> search = esGoodsRepository.search(queryBuilder, pageRequest);

        if (search != null){
            return new Result(true,StatusCode.OK,"商品展示成功",search);
        }
        return new Result(false,StatusCode.ERROR,"查询失败");
    }



    //根据id 删除商品
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除商品")
    public Result delete(@RequestParam( "list") List<Integer> ids) {
        int i = goodService.deleteByPrimaryKey(ids);
        if (i >= 1) {
            esGoodsService.deleteByIds(ids);
            return new Result(true, StatusCode.OK, "删除成功");
        } else {
            return new Result(true, StatusCode.ERROR, "删除失败");
        }

    }

    //根据id修改商品
    @PutMapping("/update")
    @ApiOperation(value = "修改商品")
    public Result update(@RequestBody Goods goods) {
        int i = goodService.updateByPrimaryKeySelective(goods);
        if (i == 1) {
            esGoodsRepository.save(goods);
            return new Result(true, StatusCode.OK, "修改成功");
        }
        return new Result(true, StatusCode.ERROR, "修改失败");
    }

5.swagger +postman 测试

这里只测试了添加 其余自己测
在这里插入图片描述
在这里插入图片描述

总结

提示:这里对文章遇到报错总结::

1. NodeAvailableException[None of the configured nodes are availabl

在这里插入图片描述
原因是我们application.yaml配置文件出现了问题:

配置文件正确写法:

spring:
  data:
    elasticsearch:
      cluster-name: my-application
      cluster-nodes: 127.0.0.1:9300

可以看到这其中有两个配置:

cluster-name: my-application
cluster-nodes: 127.0.0.1:9300

① cluster-name
在这里插入图片描述
cluster-name的名字,在elasticsearch安装的config目录下的elasticsearch.yml文件中可以查看到,如果注释,则需要放开注释
在这里插入图片描述
在这里插入图片描述
②cluster-nodes
在这里插入图片描述
在这里插入图片描述
默认配置的9300才是对外开放的tcp端口,当然我们也可以通过配置去改变这个端口号。

2.批量删除自定义方法

Error creating bean with name ‘esGoodsRepository’: Invocation of init
method failed; nested exception is
org.springframework.data.mapping.PropertyReferenceException: No
property ids found for type Goods! Did you mean ‘id’?=

创建一个service 类

package com.buba.service;

import org.springframework.stereotype.Service;

import java.util.List;

@Service
public interface EsGoodsService {
    void deleteByIds(List<Integer> ids);
}
在这里插入代码片

创建一个实现类(实现批量删除方法)

package com.buba.service;

import com.buba.pojo.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class EsGoodsRepositoryImpl implements EsGoodsService {

    @Autowired
    private EsGoodsRepository esGoodsRepository;

    @Override
    public void deleteByIds(List<Integer> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            List<Goods> esProductList = new ArrayList<>();
            for (Integer id : ids) {
                Goods goods = new Goods();
                goods.setId(id);
                esProductList.add(goods);
            }
            esGoodsRepository.deleteAll(esProductList);
        }
    }
}

controller 调用 service 方法来实现批量删除

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/426530.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

19_I.MX6ULL_SPI实验

目录 SPI简介 I.MX6U ECSPI简介 相关寄存器 ICM-20608简介 实验源码 SPI简介 同I2C一样,SPI是很常用的通信接口,也可以通过SPI来连接众多的传感器。相比I2C接口, SPI接口的通信速度很快, I2C最多400KHz,但是SPI可以到达几十MHz。I.MX6U也有4个SPI接口,可以通过这4个SPI接…

电感为什么会有饱和电流

电感有一个重要的参数那就是饱和电流&#xff0c;饱和电流的定义是当电感感值下降30%时流过电感的电流。 那么电感为什么会有饱和电流呢&#xff1f; 这个是电感磁芯的磁化曲线&#xff0c;横坐标是磁场强度H&#xff0c;纵坐标是磁感应强度B 在磁场强度较小的时候&#xff0c;…

大数据需要学哪些内容

大数据技术是当今互联网时代的热点之一&#xff0c;目前已经成为了各行各业中的最佳选择。随着物联网、人工智能、云计算等技术的发展&#xff0c;数据的规模不断增大&#xff0c;数据分析、数据挖掘、人工智能等应用也随之蓬勃发展&#xff0c;对大数据开发的需求越来越多。因…

智能网卡-提升网络性能的新选择

一、智能网口介绍 智能网卡&#xff08;Smart NIC&#xff09;是一种专用于网络数据处理的高性能网卡&#xff0c;采用了定制芯片、高速网络接口和强大的软件支持&#xff0c;可以为数据中心和企业网络提供更快、更安全、更可靠的网络连接和数据传输服务。 智能网卡的出现受到…

教你使用Apache搭建Http

Apache2默认采用的是80端口号&#xff0c;因此直接通过公网ip或域名就能访问。现实中&#xff0c;很多服务器本身就部署了许多其它服务&#xff0c;80端口号往往被占用&#xff0c;因此就需要将Apache2改成其它访问端口。 修改端口&#xff0c;首先需要修改/etc/apache2/ports…

数组排序详解

数组排序详解1、排序算法小结2、排序算法原理及实现2.1 归并排序2.2 快速排序2.3 冒泡排序2.4 插入排序2.5 选择排序2.6 希尔排序&#xff1a;1、排序算法小结 排序算法可以分为两大类&#xff1a; &#xff08;1&#xff09;非线性时间排序算法&#xff1a;通过比较来决定元素…

用Python实现批量翻译文档文件

文件名批量翻译需要用到编程语言和相应的翻译 API&#xff0c;下面以 Python 和 Google 翻译 API 为例&#xff0c;介绍具体的实现步骤&#xff1a; 安装必要的 Python 库 使用 Python 代码进行文件名翻译需要先安装两个库&#xff1a;googletrans 和 os。 pip install googl…

全网最全的Cookie, Session, Token鉴权详解,一定让你大饱眼福

目录 前言 一、Cookie鉴权 二、Session鉴权 ​编辑 三、Token鉴权 四、总结 前言 在Web开发中&#xff0c;鉴权是保护用户数据和系统安全的重要手段之一。常见的鉴权方式包括Cookie、Session和Token三种&#xff0c;下面我将详细介绍这三种鉴权方式&#xff0c;并且探讨它…

FMC子卡设计资料:ADRV9002双窄带宽带射频收发器 AD9361双收双发射频 DA子卡 ADRV9009双收双发射频FMC子卡

FMC550-基于ADRV9002双窄带宽带射频收发器FMC子卡 一、产品概述 ADRV9002 是一款高性能、高线性度、高动态范围收发器&#xff0c;旨在针对性能与功耗系统进行优化。该设备是可配置的&#xff0c;非常适合要求苛刻、低功耗、便携式和电池供电的设备。ADRV9002 的工作频率为…

基于典型相关分析的故障检测和过程监控算法研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5;&#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。⛳座右铭&#…

分布式消息中间件概念

对于分布式消息中间件&#xff0c;首先要了解两个基础的概念&#xff0c;即什么是分布式系统&#xff0c;什么又是中间件。 分布式系统 “A distributed system is one in which components located at networked computers communicate and coordinate their actions only by …

Java 中常用的版本对应关系,springboot springcloud,cloud-alibaba

1.网址链接&官方文档链接 SpringCloud与SpringBoot的版本对应关系:https://start.spring.io/actuator/info SpringBoot版本列表&#xff1a;https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent SpringBoot最新GA版官方文档&#…

【计算机网络——制作双绞线】

文章目录实验目的:实验内容及过程记录&#xff08;一&#xff09;剪线&#xff08;二&#xff09;剥皮&#xff08;三&#xff09;排序&#xff08;四&#xff09;剪齐&#xff08;五&#xff09;插入&#xff08;六&#xff09;压制&#xff1a;&#xff08;七&#xff09;检测…

vscode debug Attach mode

Python Debug Mode: 常规debug。针对*.py python脚本启动的场景。 在使用vscode debug时&#xff0c;如果调试python脚本其实很简单。 .vscode/launch.json文件。 {"version": "0.2.0","configurations": [{"name": "Python: C…

7年经验,功能测试工程师该如何一步步提升自己的能力呢?

功能测试&#xff08;所谓“点点点”&#xff09;在行业中基本能拿到10k左右的薪水&#xff0c;但是你不可能一直点。入行3年后&#xff0c;你需要拥有不止点点点的技能&#xff0c;否则出去面试&#xff0c;你会就会感受到竞争者给你带来的压力&#xff0c;你需要拿出更高级的…

真题详解(Flynn分类)-软件设计(四十六)

真题详解&#xff08;计算机总线&#xff09;-软件设计&#xff08;四十五)https://blog.csdn.net/ke1ying/article/details/130046829 Flynn分类将计算机分为四类。 单指令流单数据流机器&#xff08;SISD&#xff09;&#xff1a;早期的机器&#xff0c;在某个时钟周期&…

C++中的输入输出流iostream、文件流fstream、字符串流sstream解释

文章目录前言流的理解流的优势C中流的分类IO流字符串流sstream基本概念使用文件流fstream文本文件写文件读文件前言 流的解释。 流的理解 流的本质是一种对象。 流是介于数据和程序之间的一个中转设备。 因为流的存在&#xff0c;使得我们可以不需要直接操作数据&#xff…

瑞吉外卖Linux

1、linux简介 Linux系统版本 Linux系统分为内核版和发行版 内核版&#xff1a; 由LinusTorvalds及其团队开发、维护 免费、开源 负责控制硬件 发行版&#xff1a; 基于Linux内核版进行扩展 由各个Linux厂商开发、维护 有收费…

自动插入匹配与标题相关的百度图片或者搜狗图片软件-批量插入txt文档-Chatgpt批量写文章配图神器

1、我们用《Chatgpt 3.5-turbo软件》批量生成txt文档&#xff0c;但是这样txt文档里不带图片&#xff0c;直接发布到网站上&#xff0c;光有文字没有图片&#xff0c;效果也不是很理想&#xff0c;就需要一款配图软件。 2、该软件根据txt标题自动匹配百度图片或者搜狗图片里的…

Redis高可用

最近离职后还没开始找工作&#xff0c;在找工作前去学习一下Redis高可用方案。 目录Redis高可用高可用的概念实现方式持久化主从复制简单结构优化结构优缺点哨兵模式&#xff08;Sentinel&#xff09;哨兵进程的作用自动故障迁移(Automatic failover)优缺点集群优缺点Redis高可…