ElasticsearchRestTemplate 和ElasticsearchRepository 的使用
目录
一、使用ElasticsearchRestTemplate类
1.引用Maven类库
2. 配置文件application.yml
3.创建实体类(用于JSON文档对象的转换)
二、使用ElasticsearchRepository 类
1.引用Maven类库
2. 配置文件application.yml
3. ElasticsearchRepository接口的源码
4.CrudRepository 源码
5. 查询查找策略
5.1存储库方法可以定义为具有以下返回类型,用于返回多个元素:
5.2 使用@Query注解
6.开发实例:
操作ElasticSearch的数据,有两种方式一种是 ElasticsearchRepository 接口,另一种是ElasticsearchTemplate接口。SpringData对ES的封装ElasticsearchRestTemplate类,可直接使用,此类在ElasticsearchRestTemplate基础上进行性一定程度的封装,使用起来更方便灵活,拓展性更强。ElasticsearchRepository可以被继承操作ES,是SpringBoot对ES的高度封装,操作最为方便,但牺牲了灵活性。
Spring boot 和Elasticsearch版本关系:
一、使用ElasticsearchRestTemplate类
1.引用Maven类库
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2. 配置文件application.yml
spring:elasticsearch:rest:uris: http://192.168.10.202:9200connection-timeout: 1sread-timeout: 1musername: elasticpassword: elastic
注意,如果es资源没有开启x-pack安全插件的话,可以不加username和password(因为默认是没有的)。
3.创建实体类(用于JSON文档对象的转换)
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.time.LocalDate;
import java.time.LocalDateTime;
/*** @author Sinbad* @description: 测试ES对象<br />* @date 2022/8/26 17:12*/
@Document(indexName = "mysql-test")
@Data
public class TestEsEntity {@Id Long id;@Field(type = FieldType.Text, name = "addr")String addr;@Field(type = FieldType.Text, name = "name")String name;@Field(type = FieldType.Date, name = "birthday", pattern = "yyyy-MM-dd")LocalDate birthday;@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8",locale = "zh_CN")@Field(type = FieldType.Date, name = "create_time", pattern = "yyyy-MM-dd HH:mm:ss",format =DateFormat.custom )LocalDateTime createTime;
}
@Document注解:表示对应一个索引名相关的文档
@Data注解:lombok的,为类提供读写属性, 此外还提供了 equals()、hashCode()、toString() 方法
@Id 注解:表示文档的ID字段
@Field注解:文档字段的注解,对于日期含时间的字段,要写patten和format,不然会无法更新文档对象
@JsonFormat注解:将文档转换成JSON返回给前端时用到
注意日期类型字段不要用java.util.Date类型,要用java.time.LocalDate或java.time.LocalDateTime类型。
测试实例:
import com.hkyctech.commons.base.entity.JsonResult;
import com.hkyctech.tu.core.vo.TestEsEntity ;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;@Slf4j
@Service
public class ElasticSearchServiceImpl {@ResourceElasticsearchRestTemplate elasticsearchTemplate; //直接注入就可以用了/**** @description 查询全部数据*/public Object testSearchAll(){Query query=elasticsearchTemplate.matchAllQuery();return elasticsearchTemplate.search(query, TestEsEntity .class);}/**** @description 精确查询地址字段* @param keyword 搜索关键字*/public Object testSearchAddr(String keyword) {NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()//查询条件.withQuery(QueryBuilders.queryStringQuery(keyword).defaultField("addr"))//分页.withPageable(PageRequest.of(0, 10))//高亮字段显示.withHighlightFields(new HighlightBuilder.Field(keyword)).build();return elasticsearchTemplate.search(nativeSearchQuery, TestEsEntity .class);}/**** @description 组合查询,查询关键词不分词,关系and*/public Object testComboSearchAnd(){BoolQueryBuilder esQuery=QueryBuilders.boolQuery().must(QueryBuilders.termQuery("addr", "深圳")).must(QueryBuilders.termQuery("addr", "广东"));NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()//查询条件.withQuery(esQuery)//分页.withPageable(PageRequest.of(0, 10)).build();return elasticsearchTemplate.search(nativeSearchQuery, TestEsEntity .class);}/**** @description 组合查询,查询关键词不分词,关系or*/public Object testComboSearchOr(){BoolQueryBuilder esQuery=QueryBuilders.boolQuery().should(QueryBuilders.termQuery("addr", "深圳")).should(QueryBuilders.termQuery("addr", "广东"));NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()//查询条件.withQuery(esQuery)//分页.withPageable(PageRequest.of(0, 10)).build();return elasticsearchTemplate.search(nativeSearchQuery, TestEsEntity .class);}/**** @description 索引或更新文档* @param vo 文档对象*/public JsonResult testPutDocument(TestEsEntity vo){try {Object data = elasticsearchTemplate.save(vo);return JsonResult.getSuccessResult(data,"更新成功");}catch (Exception e){// 看http请求响应日志其实操作成功了,但是会报解析出错,可能是spring的bug,这里拦截一下String message=e.getMessage();if(message.indexOf("response=HTTP/1.1 200 OK")>0 || message.indexOf("response=HTTP/1.1 201 Created")>0){return JsonResult.getSuccessResult("更新成功");}return JsonResult.getFailResult(e.getStackTrace(),e.getMessage());}}/**** @description 删除文档* @param id 文档ID*/public JsonResult deleteDocument(String id){try {elasticsearchTemplate.delete(id, TestEsEntity .class);return JsonResult.getSuccessResult("删除成功");}catch (Exception e){String message=e.getMessage();// 看http请求响应日志其实操作成功了,但是会报解析出错,可能是spring的bug,这里拦截一下if(message.indexOf("response=HTTP/1.1 200 OK")>0 ){return JsonResult.getSuccessResult("删除成功");}return JsonResult.getFailResult(e.getStackTrace(),e.getMessage());}}
}
二、使用ElasticsearchRepository 类
1.引用Maven类库
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>
2. 配置文件application.yml
spring:elasticsearch:rest:uris: http://192.168.10.202:9200connection-timeout: 1sread-timeout: 1musername: elasticpassword: elastic
3. ElasticsearchRepository接口的源码
package org.springframework.data.elasticsearch.repository;import java.io.Serializable;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.SearchQuery;
import org.springframework.data.repository.NoRepositoryBean;@NoRepositoryBean
public interface ElasticsearchRepository<T, ID extends Serializable> extends ElasticsearchCrudRepository<T, ID> {<S extends T> S index(S entity);Iterable<T> search(QueryBuilder query);Page<T> search(QueryBuilder query, Pageable pageable);Page<T> search(SearchQuery searchQuery);Page<T> searchSimilar(T entity, String[] fields, Pageable pageable);void refresh();Class<T> getEntityClass();
}
4.CrudRepository 源码
package org.springframework.data.repository;import java.util.Optional;/*** Interface for generic CRUD operations on a repository for a specific type.** @author Oliver Gierke* @author Eberhard Wolff*/
@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {/*** Saves a given entity. Use the returned instance for further operations as the save operation might have changed the* entity instance completely.** @param entity must not be {@literal null}.* @return the saved entity will never be {@literal null}.*/<S extends T> S save(S entity);/*** Saves all given entities.** @param entities must not be {@literal null}.* @return the saved entities will never be {@literal null}.* @throws IllegalArgumentException in case the given entity is {@literal null}.*/<S extends T> Iterable<S> saveAll(Iterable<S> entities);/*** Retrieves an entity by its id.** @param id must not be {@literal null}.* @return the entity with the given id or {@literal Optional#empty()} if none found* @throws IllegalArgumentException if {@code id} is {@literal null}.*/Optional<T> findById(ID id);/*** Returns whether an entity with the given id exists.** @param id must not be {@literal null}.* @return {@literal true} if an entity with the given id exists, {@literal false} otherwise.* @throws IllegalArgumentException if {@code id} is {@literal null}.*/boolean existsById(ID id);/*** Returns all instances of the type.** @return all entities*/Iterable<T> findAll();/*** Returns all instances of the type with the given IDs.** @param ids* @return*/Iterable<T> findAllById(Iterable<ID> ids);/*** Returns the number of entities available.** @return the number of entities*/long count();/*** Deletes the entity with the given id.** @param id must not be {@literal null}.* @throws IllegalArgumentException in case the given {@code id} is {@literal null}*/void deleteById(ID id);/*** Deletes a given entity.** @param entity* @throws IllegalArgumentException in case the given entity is {@literal null}.*/void delete(T entity);/*** Deletes the given entities.** @param entities* @throws IllegalArgumentException in case the given {@link Iterable} is {@literal null}.*/void deleteAll(Iterable<? extends T> entities);/*** Deletes all entities managed by the repository.*/void deleteAll();
}
5. 查询查找策略
5.1存储库方法可以定义为具有以下返回类型,用于返回多个元素:
-
List<T>
-
Stream<T>
-
SearchHits<T>
-
List<SearchHit<T>>
-
Stream<SearchHit<T>>
-
SearchPage<T>
5.2 使用@Query注解
使用@query注释对方法声明query。
interface BookRepository extends ElasticsearchRepository<Book, String> {@Query("{\"match\": {\"name\": {\"query\": \"?0\"}}}")Page<Book> findByName(String name,Pageable pageable);
}
设置为注释参数的字符串必须是有效的 Elasticsearch JSON 查询。 它将作为查询元素的值发送到Easticsearch;例如,如果使用参数 John 调用函数,它将生成以下查询正文:
{"query": {"match": {"name": {"query": "John"}}}
}
对@Query
采用集合参数的方法进行注释
@Query("{\"ids\": {\"values\": ?0 }}")
List<SampleEntity> getByIds(Collection<String> ids);
将进行ID查询以返回所有匹配的文档。因此,调用List为[“id1”、“id2”、“id3”]的方法将生成查询主体
{"query": {"ids": {"values": ["id1", "id2", "id3"]}}
}
6.开发实例:
public interface LogRepository extends ElasticsearchRepository<Log, String> {/*** 定义一个方法查询:根据title查询es** 原因: ElasticsearchRepository会分析方法名,参数对应es中的field(这就是灵活之处)* @param title*/List<Log> findBySummary(String summary);List<Log> findByTitle(String title);/*** 定义一个方法查询: 根据title,content查询es*/List<Log> findByTitleAndContent(String title, String content);}
@PostMapping("save")public void save(@Validated @RequestBody Log req){Log dto = new Log();dto.setTitle(req.getTitle());dto.setSummary(req.getSummary());dto.setContent(req.getContent());dto.setCreateTime(new Date());dto.setId(req.getId()); LogRepository.save(dto);return ;} @PostMapping("testTitle")public void testSearchTitle(@Validated @RequestBody Log req){List<Log> searchResult = logRepository.findByTitle(req.getMobileType());Iterator<Log> iterator = searchResult.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}System.out.println("sa");return;}
官网:Spring Data Elasticsearch - Reference Documentation
相关文章:

ElasticsearchRestTemplate 和ElasticsearchRepository 的使用
目录 一、使用ElasticsearchRestTemplate类 1.引用Maven类库 2. 配置文件application.yml 3.创建实体类(用于JSON文档对象的转换) 二、使用ElasticsearchRepository 类 1.引用Maven类库 2. 配置文件application.yml 3. ElasticsearchRepository接…...

Typora +Picgo 搭建个人笔记
文章目录 Typora Picgo 搭建个人笔记一、Picgo Github 搭建图床1.基础设置2. 将配置导出,方便下次使用 二、Typora:设置 :1. 基本设置2. 导出自动提交3. 备份图片 Typora Picgo 搭建个人笔记 typora 下载地址: https://zahui.fan…...
八、K8S之HPA自动扩缩容
HPA 一、概念 HPA(Horizontal Pod Autoscaler,水平 Pod 自动伸缩)是 Kubernetes 中的一种特性,其作用是根据资源使用情况自动调整 Pod 的副本数,以实现应用程序的自动扩展和收缩。 HPA 可以根据 CPU 使用率或其他自…...

损失函数总结(二):L1Loss、MSELoss
损失函数总结(二):L1Loss、MSELoss 1 引言2 损失函数2.1 L1Loss2.2 MSELoss 3 总结 1 引言 在上一篇博文中介绍了损失函数是什么以及为什么使用损失函数,从这一篇博文就开始关于损失函数有哪些进行进一步的介绍。这里放一张损失函…...
力扣(LeetCode)2530. 执行 K 次操作后的最大分数(C++)
贪心优先队列 请看答案需求:得到最大分数。易猜到,得到最大分数的取法是每次取数组中最大的数字(贪心思路)。 问题转化为:如何快速找到数组中最大的数字,根据问题规模 k 1 0 5 k10^5 k105,维护优先队列即可 O ( k l…...

C# 快速简单反射操作
文章目录 前言新反射使用BindingFlags以公有属性使用举例运行结果 前言 我之前写过一篇博客,是关于C# 反射的,我那时候使用的C# 反射写起来还是比较麻烦,需要获取Properies,再遍历Property,再找到对应Property,再使用…...

【python高级】设计模式、类工厂、对象工厂
一、说明 最近试着读Design pattern, 不过有些概念实在太抽象了, 整理一下自己所学抽象工厂的精神,就是要有abstract class(not implement),而所有不同种类的对象,都是继承这个abstract class&a…...

Flink的算子列表状态的使用
背景 算子的列表状态是平时比较常见的一种状态,本文通过官方的例子来看一下怎么使用算子列表状态 算子列表状态 算子列表状态支持应用的并行度扩缩容,如下所示: 使用方法参见官方示例,我加了几个注解: public class Bufferin…...

使用 Github Actions 工作流自动部署 Github Pages
GitHub-Actions actions顾名思义就是一堆动作,是一个持续集成服务,持续集成包含了拉代码、运行测试、编译代码、登录远程服务器,发布到第三方服务等等的操作,GitHub将这些操作称为actions。 概念:Workflows, Events,…...

Xposed hook 抖音账户信息
本篇主要讲下hook获取 抖音账户的相关信息,直接上代码。 public class DouHook {private static final String TAG "DouHook";public static void hook(XC_LoadPackage.LoadPackageParam lpparam) {Log.e(TAG, "DouHook start");if (lpparam …...

回顾 | E³CI效能认知与改进论坛,助力企业研发效能度量和提升
2023年8月,TiD质量竞争力大会组委会和ECI专家委员会成功举办TiD大时段课程“度量驱动研发效能提升”与“ECI效能认知与改进论坛”。与会专家以《ECI软件研发效能度量规范》团体标准为要点,为企业研发效能度量和提升分享诸多实践成果与经验。 《ECI软件研…...
科技的成就(五十二)
405、微信公众平台正式上线 "1995 年 8 月 24 日,微软发布 Windows 95。Windows 95 极大地改进了前续系统的图形用户界面,首次推出了开始菜单、任务栏、最大化、最小化窗口以及关闭按钮。此外,Windows 95 最大程度兼容当时的 MS-DOS 和 …...

【23种设计模式】装饰器模式
个人主页:金鳞踏雨 个人简介:大家好,我是金鳞,一个初出茅庐的Java小白 目前状况:22届普通本科毕业生,几经波折了,现在任职于一家国内大型知名日化公司,从事Java开发工作 我的博客&am…...

解决IDEA中SpringBoot项目创建多个子模块时配置文件小绿叶图标异常问题
在新建子模块下创建配置文件: 在子模块gateway中新建的配置文件,正常情况下配置文件左侧是小树叶标识,而这次新建application-dev.yml是个小树叶标识,bootstrap.yml是个方框。 看其他方案都是在project structure中设置,但未显示…...

【马蹄集】—— 概率论专题
概率论专题 目录 MT2226 抽奖概率MT2227 饿饿!饭饭!MT2228 甜甜花的研究MT2229 赌石MT2230 square MT2226 抽奖概率 难度:黄金 时间限制:1秒 占用内存:128M 题目描述 小码哥正在进行抽奖,箱子里有…...
Spring 6整合单元测试JUnit4和JUnit5
单元测试:JUnit 在之前的测试方法中,几乎都能看到以下的两行代码: ApplicationContext context new ClassPathXmlApplicationContext("xxx.xml"); Xxxx xxx context.getBean(Xxxx.class);这两行代码的作用是创建Spring容器&…...

【好书推荐】深入理解现代JavaScript
作者介绍 T. J. Crowder是一位拥有30年经验的软件工程师。在他的整个职业生涯中,他至少有一半时间是在使用JavaScript从事开发工作。他经营着软件承包和产品公司Farsight Software。他经常在Stack Overflow上为人们提供帮助,他是十大贡献者之一和JavaScr…...

高效协同: 打造分布式系统的三种模式
在构建分布式系统时,分布式协调是否总是必要选项?本文通过一些实际的例子讨论了这一问题,并通过把问题区分为是否具有单调性做为是否需要分布式协调的标准。原文: Avoiding Coordination Cost: Three Patterns for Building Efficient Distri…...
机器学习-无监督学习之聚类
文章目录 K均值聚类密度聚类(DBSCAN)层次聚类AGNES 算法DIANA算法 高斯混合模型聚类聚类效果的衡量指标小结 K均值聚类 步骤: Step1:随机选取样本作为初始均值向量。 Step2:计算样本点到各均值向量的距离,…...

智能垃圾桶丨悦享便捷生活
垃圾桶是人们日常生活所必不可少的必需品,它让生活中所产生的垃圾有了一个正确的存放地方。随着生产技术的迅速发展,垃圾桶也得以更新换代。由最初的简单式的圆筒式垃圾桶,到现在出现的感应式垃圾桶、智能语音控制垃圾桶,垃圾桶也…...

TDengine 快速体验(Docker 镜像方式)
简介 TDengine 可以通过安装包、Docker 镜像 及云服务快速体验 TDengine 的功能,本节首先介绍如何通过 Docker 快速体验 TDengine,然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。如果你不熟悉 Docker,请使用 安装包的方式快…...

屋顶变身“发电站” ,中天合创屋面分布式光伏发电项目顺利并网!
5月28日,中天合创屋面分布式光伏发电项目顺利并网发电,该项目位于内蒙古自治区鄂尔多斯市乌审旗,项目利用中天合创聚乙烯、聚丙烯仓库屋面作为场地建设光伏电站,总装机容量为9.96MWp。 项目投运后,每年可节约标煤3670…...

高危文件识别的常用算法:原理、应用与企业场景
高危文件识别的常用算法:原理、应用与企业场景 高危文件识别旨在检测可能导致安全威胁的文件,如包含恶意代码、敏感数据或欺诈内容的文档,在企业协同办公环境中(如Teams、Google Workspace)尤为重要。结合大模型技术&…...
DeepSeek 技术赋能无人农场协同作业:用 AI 重构农田管理 “神经网”
目录 一、引言二、DeepSeek 技术大揭秘2.1 核心架构解析2.2 关键技术剖析 三、智能农业无人农场协同作业现状3.1 发展现状概述3.2 协同作业模式介绍 四、DeepSeek 的 “农场奇妙游”4.1 数据处理与分析4.2 作物生长监测与预测4.3 病虫害防治4.4 农机协同作业调度 五、实际案例大…...

STM32HAL库USART源代码解析及应用
STM32HAL库USART源代码解析 前言STM32CubeIDE配置串口USART和UART的选择使用模式参数设置GPIO配置DMA配置中断配置硬件流控制使能生成代码解析和使用方法串口初始化__UART_HandleTypeDef结构体浅析HAL库代码实际使用方法使用轮询方式发送使用轮询方式接收使用中断方式发送使用中…...

Linux中《基础IO》详细介绍
目录 理解"文件"狭义理解广义理解文件操作的归类认知系统角度文件类别 回顾C文件接口打开文件写文件读文件稍作修改,实现简单cat命令 输出信息到显示器,你有哪些方法stdin & stdout & stderr打开文件的方式 系统⽂件I/O⼀种传递标志位…...
C#最佳实践:为何优先使用as或is而非强制转换
C#最佳实践:为何优先使用as或is而非强制转换 在 C# 的编程世界里,类型转换是我们经常会遇到的操作。就像在现实生活中,我们可能需要把不同形状的物品重新整理归类一样,在代码里,我们也常常需要将一个数据类型转换为另…...

性能优化中,多面体模型基本原理
1)多面体编译技术是一种基于多面体模型的程序分析和优化技术,它将程序 中的语句实例、访问关系、依赖关系和调度等信息映射到多维空间中的几何对 象,通过对这些几何对象进行几何操作和线性代数计算来进行程序的分析和优 化。 其中࿰…...

【笔记】结合 Conda任意创建和配置不同 Python 版本的双轨隔离的 Poetry 虚拟环境
如何结合 Conda 任意创建和配置不同 Python 版本的双轨隔离的Poetry 虚拟环境? 在 Python 开发中,为不同项目配置独立且适配的虚拟环境至关重要。结合 Conda 和 Poetry 工具,能高效创建不同 Python 版本的 Poetry 虚拟环境,接下来…...

uni-app学习笔记二十七--设置底部菜单TabBar的样式
官方文档地址:uni.setTabBarItem(OBJECT) | uni-app官网 uni.setTabBarItem(OBJECT) 动态设置 tabBar 某一项的内容,通常写在项目的App.vue的onLaunch方法中,用于项目启动时立即执行 重要参数: indexnumber是tabBar 的哪一项&…...