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

【Elasticsearch】spring-boot-starter-data-elasticsearch的使用以及Elasticsearch集群的连接

更多有关博主写的往期Elasticsearch文章

标题地址
【ElasticSearch 集群】Linux安装ElasticSearch集群(图文解说详细版)https://masiyi.blog.csdn.net/article/details/131109454
基于SpringBoot+ElasticSearch 的Java底层框架的实现https://masiyi.blog.csdn.net/article/details/121534307
ElasticSearch对标Mysql,谁能拔得头筹?https://masiyi.blog.csdn.net/article/details/122661822
同事说关键字查询用Mysql,我上去就是一个高压锅,用ElasticSearch不香吗?https://masiyi.blog.csdn.net/article/details/122701654
新年第一天,老板让升级ElasticSearch版本,我说得加钱https://masiyi.blog.csdn.net/article/details/122819455
使用了ElasticSearch之后,公司系统查询速度快了50倍,工资直接翻一倍https://masiyi.blog.csdn.net/article/details/122819455
ElasticSearch实战教程PostMan版(超级详细版)https://masiyi.blog.csdn.net/article/details/123048119
Linux安装ElasticSearch以及Ik分词器(图文解说详细版)https://masiyi.blog.csdn.net/article/details/121509681

文章目录

    • 🐝第一步,创建一个springboot项目
    • 🐝第二步,导入spring-boot-starter-data-elasticsearch依赖
    • 🐝第三步,配置yml文件
    • 🐝第四步,编写es索引对应的实体类
    • 🐝第五步,编写实体类对应的mapper
    • 🐝第六步,使用框架自带的增删改查
      • 🐝增
        • 🐝使用ElasticsearchRestTemplate
        • 🐝使用mapper
        • 🐝设置指定的id
        • 🐝批量保存
      • 🐝删
        • 🐝传入实体类删
        • 🐝传入id删
        • 🐝删除索引里面所有的数据(慎用)
      • 🐝改
        • 🐝实体改
        • 🐝实体改全部
        • 🐝先查再update
        • 🐝直接使用局部更新
      • 🐝查
        • 🐝根据id查
        • 🐝根据id列表查
        • 🐝查询全部数据
        • 🐝排序查-正序
        • 🐝排序查-倒序
        • 🐝分页查
        • 🐝自定义复杂的查询
    • 🐝第七步,使用JPA风格的查询方式
        • 🐝根据age查询
        • 🐝查询所有符合age的数据
        • 🐝查询最top的数据

导语

发现很多公司都是自己导入原生的jar包自己去封装一套Elasticsearch的框架,这样虽然可以自定义业务,但是需要花费很多的时间,其实spring官方有一套springboot的starter,帮助大家快速入手官网的starter,这篇博客也会介绍使用该starter连接Elasticsearch的集群。该starter有点像mybatisplus+Jpa,如果熟悉这两个框架的同学应该很快就会上手。

官网地址:
https://docs.spring.io/spring-data/elasticsearch/docs/4.0.x/reference/html/#preface

本文所有的代码都已经提交到git仓库中,仓库地址:
https://gitee.com/WangFuGui-Ma/spring-boot-elasticSearch

在这里插入图片描述

现在我们开始按照步骤进行spring-boot-starter-data-elasticsearch的使用,本文中使用的spring boot版本为2.7.x 对于的elasticsearch客户端版本为7.17.x

🐝第一步,创建一个springboot项目

在这里插入图片描述

🐝第二步,导入spring-boot-starter-data-elasticsearch依赖

		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>

其他依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--json--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency><!--json-->

在这里插入图片描述

🐝第三步,配置yml文件

spring:elasticsearch:uris:- 192.168.75.128:9200- 192.168.75.129:9200- 192.168.75.130:9200
server:port: 8889

uris这里填的是集群的地址,如果你的es是单机版的,直接填一个就行了

🐝第四步,编写es索引对应的实体类

import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.WriteTypeHint;/*** @Author masiyi* @Date 2023/6/14 13:46* @PackageName:com.masiyi.springbootstarterdataelasticsearch.doman* @ClassName: ElasticTest* @Description: TODO* @Version 1.0*/
@Data
@Document(indexName = "elastic_test",writeTypeHint = WriteTypeHint.FALSE)
public class ElasticTest {private Long id;private String name;private Integer age;private Boolean isMan;
}

注:

  • id这个类型一定要写,否则会报错
  • indexName对应es中的索引
  • writeTypeHint如果为false则不会自动创建索引

🐝第五步,编写实体类对应的mapper

类似mybatis一样,我们需要创建对应的mapper

public interface ElasticTestMapper extends ElasticsearchRepository<ElasticTest,Long> {}

继承ElasticsearchRepository类,第一个泛型添es对应的实体类,第二个泛型添id的类型

🐝第六步,使用框架自带的增删改查

我们这次用单元测试的方法跟大家演示框架的用法

在这里插入图片描述

注入刚刚创建的mapper和框架的ElasticsearchRestTemplate

🐝增

🐝使用ElasticsearchRestTemplate

   @Testvoid save() {ElasticTest elasticTest = new ElasticTest();elasticTest.setName("李四");elasticTest.setAge(23);elasticTest.setIsMan(true);elasticsearchTemplate.save(elasticTest);}

🐝使用mapper

    @Testvoid insert() {ElasticTest elasticTest = new ElasticTest();elasticTest.setName("李四");elasticTest.setAge(23);elasticTest.setIsMan(true);elasticTestMapper.save(elasticTest);}

🐝设置指定的id

   @Testvoid insertId() {ElasticTest elasticTest = new ElasticTest();elasticTest.setName("掉头发的王富贵");elasticTest.setAge(25);elasticTest.setIsMan(true);elasticTest.setId(2434235L);elasticTestMapper.save(elasticTest);}

🐝批量保存

    @Testvoid saveAll() {ElasticTest elasticTest = new ElasticTest();elasticTest.setName("李四");elasticTest.setAge(24);elasticTest.setIsMan(true);elasticTestMapper.saveAll(Arrays.asList(elasticTest));}

🐝删

🐝传入实体类删

    @Testvoid delete() {ElasticTest elasticTest = new ElasticTest();elasticTest.setId(2342342L);elasticTestMapper.delete(elasticTest);}

🐝传入id删

    @Testvoid deleteById() {elasticTestMapper.deleteById(2342342L);}

🐝删除索引里面所有的数据(慎用)

    @Testvoid deleteAll() {elasticTestMapper.deleteAll();}

🐝改

🐝实体改

    @Testvoid update() {ElasticTest elasticTest = new ElasticTest();elasticTest.setName("掉头发的王富贵hh");elasticTest.setId(2434235L);elasticTestMapper.save(elasticTest);}

这里改会把其他的不在实体里面为null的数据清空

在这里插入图片描述

🐝实体改全部

 @Testvoid updateAll() {ElasticTest elasticTest = new ElasticTest();elasticTest.setName("掉头发的王富贵");elasticTest.setAge(24);elasticTest.setIsMan(true);elasticTest.setId(2434234L);elasticTestMapper.save(elasticTest);}

如果我们只需要局部更新,可以使用下面的两种方法

🐝先查再update

    @Testvoid updateNow() {ElasticTest elasticTest = elasticTestMapper.findById(2434234L).get();elasticTest.setName("不掉头发的王富贵");elasticTestMapper.save(elasticTest);}

但是这个方法会消耗性能,所以推荐用下面的方法

🐝直接使用局部更新

    @Testvoid updateNow2() {ElasticTest elasticTest = new ElasticTest();elasticTest.setName("掉头发的王富贵h");Map map = JSONObject.parseObject(JSONObject.toJSONString(elasticTest), Map.class);UpdateQuery updateQuery = UpdateQuery.builder("0ZUv7okBcQy9f7u_tXkH").withDocument(Document.from(map)).build();elasticsearchTemplate.update(updateQuery, IndexCoordinates.of("elastic_test"));}

在这里插入图片描述

🐝查

🐝根据id查

    @Testvoid select() {Optional<ElasticTest> byId = elasticTestMapper.findById(2434234L);byId.ifPresent(System.out::println);}

🐝根据id列表查

  @Testvoid findAllById() {Iterable<ElasticTest> allById = elasticTestMapper.findAllById(Arrays.asList(2434234L));allById.forEach(System.out::println);}

🐝查询全部数据

    @Testvoid findAll() {Iterable<ElasticTest> allById = elasticTestMapper.findAll();allById.forEach(System.out::println);}

🐝排序查-正序

    @Testvoid findAllSort() {Sort age = Sort.by("age").ascending();Iterable<ElasticTest> all = elasticTestMapper.findAll(age);all.forEach(System.out::println);}

🐝排序查-倒序

    @Testvoid findAllSortDE() {Sort age = Sort.by("age").descending();Iterable<ElasticTest> all = elasticTestMapper.findAll(age);all.forEach(System.out::println);}

🐝分页查

    @Testvoid findAllPage() {PageRequest pageRequest = PageRequest.of(0, 10);Page<ElasticTest> all = elasticTestMapper.findAll(pageRequest);all.forEach(System.out::println);System.out.println(JSON.toJSONString(all));}

🐝自定义复杂的查询

 @Testvoid findMyStyle() {TermQueryBuilder termQueryBuilder = new TermQueryBuilder("name.keyword", "掉头发的王富贵");NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(termQueryBuilder);SearchHits<ElasticTest> search = elasticsearchTemplate.search(nativeSearchQuery, ElasticTest.class);List<SearchHit<ElasticTest>> hitList = search.getSearchHits();for (SearchHit<ElasticTest> hit : hitList) {ElasticTest entity = hit.getContent(); // 获取实体对象System.out.println(entity);String index = hit.getIndex(); // 获取索引名System.out.println(index);}}

🐝第七步,使用JPA风格的查询方式

如果会用jpa的同学看到这个可能会非常得熟悉

在这里插入图片描述
可以自定义查询方法find...

🐝根据age查询

    ElasticTest findByAge(Integer age);

🐝查询所有符合age的数据

    List<ElasticTest> findAllByAge(Integer age);

🐝查询最top的数据

    ElasticTest findTopByAge(Integer age);

如果你使用的是idea这种高级的编辑器,你在mapper写方法的时候会自动提示你。

在这里插入图片描述

通过本文的学习,我们探索了在Spring Boot应用中使用Elasticsearch的方法以及如何连接到Elasticsearch集群。Elasticsearch作为一款强大的搜索和分析引擎,在现代应用开发中扮演着至关重要的角色。借助于Spring Boot和spring-boot-starter-data-elasticsearch,我们能够以更加便捷的方式将Elasticsearch集成到我们的项目中,实现高效的数据搜索与分析。

通过配置简单明了的属性,我们能够快速地将Spring Boot应用连接到Elasticsearch集群,实现数据的索引、搜索和分析。借助于Spring Data Elasticsearch提供的强大功能,我们能够轻松地定义实体类、进行CRUD操作,并且利用Elasticsearch的全文搜索和分词等特性,让我们的应用具备更高效的查询和检索能力。

在这里插入图片描述

相关文章:

【Elasticsearch】spring-boot-starter-data-elasticsearch的使用以及Elasticsearch集群的连接

更多有关博主写的往期Elasticsearch文章 标题地址【ElasticSearch 集群】Linux安装ElasticSearch集群&#xff08;图文解说详细版&#xff09;https://masiyi.blog.csdn.net/article/details/131109454基于SpringBootElasticSearch 的Java底层框架的实现https://masiyi.blog.c…...

Python学习笔记_进阶篇(四)_django知识(三)

本章内容&#xff1a; Django 发送邮件Django cookieDjango sessionDjango CSRF Django 发送邮件 我们常常会用到一些发送邮件的功能&#xff0c;比如有人提交了应聘的表单&#xff0c;可以向HR的邮箱发邮件&#xff0c;这样&#xff0c;HR不看网站就可以知道有人在网站上提…...

指针(初阶)

1. 指针是什么&#xff1f; 指针是什么&#xff1f; 指针理解的2个要点&#xff1a; 1. 指针是内存中一个最小单元的编号&#xff0c;也就是地址 2. 平时口语中说的指针&#xff0c;通常指的是指针变量&#xff0c;是用来存放内存地址的变量 总结&#xff1a;指针就是地址&…...

Flink内核源码解析--Flink中重要的工作组件和机制

Flink内核源码 1、掌握Flink应用程序抽象2、掌握Flink核心组件整体架构抽象3、掌握Flink Job三种运行模式4、理解Flink RPC网络通信框架Akka详解5、理解TaskManager为例子&#xff0c;分析Flink封装Akka Actor的方法和整个调用流程6、理解Flink高可用服务HighAvailabilityServ…...

Linux 压缩解压(归档管理):tar命令

计算机中的数据经常需要备份&#xff0c;tar是Unix/Linux中最常用的备份工具&#xff0c;此命令可以把一系列文件归档到一个大文件中&#xff0c;也可以把档案文件解开以恢复数据。 tar使用格式 tar [参数] 打包文件名 文件 tar命令很特殊&#xff0c;其参数前面可以使用“-”&…...

spring boot集成mqtt协议发送和订阅数据

maven的pom.xml引入包 <!--mqtt--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-integration</artifactId><version>2.3.6.RELEASE</version></dependency><dependency…...

【数据库】详解数据库架构优化思路(两主架构、主从复制、冷热分离)

文章目录 1、为什么对数据库做优化2、双主架构双主架构的工作方式如下&#xff1a;双主架构的优势包括&#xff1a;但是一般不用这种架构&#xff0c;原因是&#xff1a; 3、主从复制主从复制的工作方式如下&#xff1a;主从复制的优势包括&#xff1a;主从复制的缺点 4、冷热分…...

el-table 实现动态表头 静态内容 根据数据显示动态输入框

直接放代码了 <el-table:data"form.tableDataA"borderstripestyle"width: 100%; margin-top: 20px"><el-table-columnv-for"(category, categoryIndex) in form.tableDataA":key"categoryIndex":label"category.name&qu…...

Reids 的整合 Spring Data Redis使用

大家好 , 我是苏麟 , 今天带来强大的Redis . REmote DIctionary Server(Redis) 是一个由 Salvatore Sanfilippo 写的 key-value 存储系统&#xff0c;是跨平台的非关系型数据库。 Redis 是一个开源的使用 ANSI C 语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式、可选…...

3D数据转换工具HOOPS Exchange概览

HOOPS Exchange SDK是一组C软件库&#xff0c;使开发团队能够快速为其应用程序添加可靠的2D和3D CAD导入和导出功能。这允许访问广泛的数据&#xff0c;包括边界表示&#xff08;BREP&#xff09;、产品制造信息&#xff08;PMI&#xff09;、模型树、视图、持久ID、样式、构造…...

【从零开始的rust web开发之路 一】axum学习使用

系列文章目录 第一章 axum学习使用 文章目录 系列文章目录前言老规矩先看官方文档介绍高级功能兼容性 二、hello world三、路由四&#xff0c;handler和提取器五&#xff0c;响应 前言 本职java开发&#xff0c;兼架构设计。空闲时间学习了rust&#xff0c;目前还不熟练掌握。…...

oracle警告日志\跟踪日志磁盘空间清理

oracle警告日志\跟踪日志磁盘空间清理 问题现象&#xff1a; 通过查看排查到alert和tarce占用大量磁盘空间 警告日志 /u01/app/oracle/diag/rdbms/orcl/orcl/alert 跟踪日志 /u01/app/oracle/diag/rdbms/orcl/orcl/trace 解决方案&#xff1a; 用adrci清除日志 确定目…...

【vue】el-table 数据更新后,刷新表格数据

表格里面的数据更新后&#xff0c;可以通过以下方法来刷新表格 方法1 用更新后的数据&#xff0c;覆盖之前的数据 var newTableData[];for(var i0;i<that.tableData.length;i){ if(aIdthat.selectStationId&&bIdthat.selectDeviceId){that.tableData[i].physica…...

AVL——平衡搜索树

✅<1>主页&#xff1a;我的代码爱吃辣&#x1f4c3;<2>知识讲解&#xff1a;数据结构——AVL树☂️<3>开发环境&#xff1a;Visual Studio 2022&#x1f4ac;<4>前言&#xff1a;AVL树是对二叉搜索树的严格高度控制&#xff0c;所以AVL树的搜索效率很高…...

TCP通信流程以及一些TCP的相关概念

1.TCP和UDP区别 都为传输层协议 UDP&#xff1a;用户数据报协议&#xff0c;面向无连接&#xff0c;可以单播&#xff0c;多播&#xff0c;广播&#xff0c;面向数据报&#xff0c;不可靠 TCP&#xff1a;传输控制协议&#xff0c;面向连接的&#xff0c;可靠的&#xff0c;基…...

PyTorch学习笔记(十七)——完整的模型验证(测试,demo)套路

完整代码&#xff1a; import torch import torchvision from PIL import Image from torch import nnimage_path "../imgs/dog.png" image Image.open(image_path) print(image)# 因为png格式是四个通道&#xff0c;除了RGB三通道外&#xff0c;还有一个透明度通…...

WPF开篇

一、为什么要学习WPF 大环境不好&#xff0c;公司要求逐年提高&#xff0c;既要会后端又要会客户端WPF相对于WinForm来说用户界面效果更好&#xff0c;图像更加立体化也是给自己增加一项技能&#xff0c;谨记一句话&#xff0c;技多不压身&#xff1b;多一份技能就多一份竞争力…...

linux 压缩解压缩

压缩解压缩 linux中压缩和解压文件也是很常见的 zip格式 zip格式的压缩包在windows很常见&#xff0c;linux中也有zip格式的压缩包 #压缩#zip [选项] 压缩包名 文件(多个文件空格隔开)zip 1.zip 123.txt 456.txt zip -r 2.zip /home/user1 ---------------------- -r 压缩目录 …...

centos9 mysql8修改数据库的存储路径

一、环境 系统&#xff1a;CentOS Stream release 9 mysql版本&#xff1a;mysql Ver 8.0.34 for Linux on x86_64 (MySQL Community Server - GPL) 二、修改mysql的数据库&#xff0c;存储路径 查看目录数据存储的位置 cat /etc/my.cnf操作 1、新建存放的目录&#xff0c;…...

【C++】<Windows编程中消息即事件的处理>

目录 一、注册窗口类&#xff0c;指定消息处理函数&#xff0c;捕获消息并发给处理函数 二、消息处理函数 三、通用窗口消息 四、其他消息 1.滚动条消息 2.按钮控件消息 3.按钮控件通知消息 4.按键消息 5.系统菜单等消息 6.组合框控件消息 7.组合框控件通知消息 8.列…...

label-studio的使用教程(导入本地路径)

文章目录 1. 准备环境2. 脚本启动2.1 Windows2.2 Linux 3. 安装label-studio机器学习后端3.1 pip安装(推荐)3.2 GitHub仓库安装 4. 后端配置4.1 yolo环境4.2 引入后端模型4.3 修改脚本4.4 启动后端 5. 标注工程5.1 创建工程5.2 配置图片路径5.3 配置工程类型标签5.4 配置模型5.…...

shell脚本--常见案例

1、自动备份文件或目录 2、批量重命名文件 3、查找并删除指定名称的文件&#xff1a; 4、批量删除文件 5、查找并替换文件内容 6、批量创建文件 7、创建文件夹并移动文件 8、在文件夹中查找文件...

Vue3 + Element Plus + TypeScript中el-transfer穿梭框组件使用详解及示例

使用详解 Element Plus 的 el-transfer 组件是一个强大的穿梭框组件&#xff0c;常用于在两个集合之间进行数据转移&#xff0c;如权限分配、数据选择等场景。下面我将详细介绍其用法并提供一个完整示例。 核心特性与用法 基本属性 v-model&#xff1a;绑定右侧列表的值&…...

SCAU期末笔记 - 数据分析与数据挖掘题库解析

这门怎么题库答案不全啊日 来简单学一下子来 一、选择题&#xff08;可多选&#xff09; 将原始数据进行集成、变换、维度规约、数值规约是在以下哪个步骤的任务?(C) A. 频繁模式挖掘 B.分类和预测 C.数据预处理 D.数据流挖掘 A. 频繁模式挖掘&#xff1a;专注于发现数据中…...

pam_env.so模块配置解析

在PAM&#xff08;Pluggable Authentication Modules&#xff09;配置中&#xff0c; /etc/pam.d/su 文件相关配置含义如下&#xff1a; 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块&#xff0c;负责验证用户身份&am…...

【开发技术】.Net使用FFmpeg视频特定帧上绘制内容

目录 一、目的 二、解决方案 2.1 什么是FFmpeg 2.2 FFmpeg主要功能 2.3 使用Xabe.FFmpeg调用FFmpeg功能 2.4 使用 FFmpeg 的 drawbox 滤镜来绘制 ROI 三、总结 一、目的 当前市场上有很多目标检测智能识别的相关算法&#xff0c;当前调用一个医疗行业的AI识别算法后返回…...

学校时钟系统,标准考场时钟系统,AI亮相2025高考,赛思时钟系统为教育公平筑起“精准防线”

2025年#高考 将在近日拉开帷幕&#xff0c;#AI 监考一度冲上热搜。当AI深度融入高考&#xff0c;#时间同步 不再是辅助功能&#xff0c;而是决定AI监考系统成败的“生命线”。 AI亮相2025高考&#xff0c;40种异常行为0.5秒精准识别 2025年高考即将拉开帷幕&#xff0c;江西、…...

rnn判断string中第一次出现a的下标

# coding:utf8 import torch import torch.nn as nn import numpy as np import random import json""" 基于pytorch的网络编写 实现一个RNN网络完成多分类任务 判断字符 a 第一次出现在字符串中的位置 """class TorchModel(nn.Module):def __in…...

华硕a豆14 Air香氛版,美学与科技的馨香融合

在快节奏的现代生活中&#xff0c;我们渴望一个能激发创想、愉悦感官的工作与生活伙伴&#xff0c;它不仅是冰冷的科技工具&#xff0c;更能触动我们内心深处的细腻情感。正是在这样的期许下&#xff0c;华硕a豆14 Air香氛版翩然而至&#xff0c;它以一种前所未有的方式&#x…...

探索Selenium:自动化测试的神奇钥匙

目录 一、Selenium 是什么1.1 定义与概念1.2 发展历程1.3 功能概述 二、Selenium 工作原理剖析2.1 架构组成2.2 工作流程2.3 通信机制 三、Selenium 的优势3.1 跨浏览器与平台支持3.2 丰富的语言支持3.3 强大的社区支持 四、Selenium 的应用场景4.1 Web 应用自动化测试4.2 数据…...