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

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.创建实体类&#xff08;用于JSON文档对象的转换&#xff09; 二、使用ElasticsearchRepository 类 1.引用Maven类库 2. 配置文件application.yml 3. ElasticsearchRepository接…...

Typora +Picgo 搭建个人笔记

文章目录 Typora Picgo 搭建个人笔记一、Picgo Github 搭建图床1.基础设置2. 将配置导出&#xff0c;方便下次使用 二、Typora&#xff1a;设置 &#xff1a;1. 基本设置2. 导出自动提交3. 备份图片 Typora Picgo 搭建个人笔记 typora 下载地址&#xff1a; https://zahui.fan…...

八、K8S之HPA自动扩缩容

HPA 一、概念 HPA&#xff08;Horizontal Pod Autoscaler&#xff0c;水平 Pod 自动伸缩&#xff09;是 Kubernetes 中的一种特性&#xff0c;其作用是根据资源使用情况自动调整 Pod 的副本数&#xff0c;以实现应用程序的自动扩展和收缩。 HPA 可以根据 CPU 使用率或其他自…...

损失函数总结(二):L1Loss、MSELoss

损失函数总结&#xff08;二&#xff09;&#xff1a;L1Loss、MSELoss 1 引言2 损失函数2.1 L1Loss2.2 MSELoss 3 总结 1 引言 在上一篇博文中介绍了损失函数是什么以及为什么使用损失函数&#xff0c;从这一篇博文就开始关于损失函数有哪些进行进一步的介绍。这里放一张损失函…...

力扣(LeetCode)2530. 执行 K 次操作后的最大分数(C++)

贪心优先队列 请看答案需求&#xff1a;得到最大分数。易猜到&#xff0c;得到最大分数的取法是每次取数组中最大的数字(贪心思路)。 问题转化为&#xff1a;如何快速找到数组中最大的数字&#xff0c;根据问题规模 k 1 0 5 k10^5 k105&#xff0c;维护优先队列即可 O ( k l…...

C# 快速简单反射操作

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

【python高级】设计模式、类工厂、对象工厂

一、说明 最近试着读Design pattern&#xff0c; 不过有些概念实在太抽象了&#xff0c; 整理一下自己所学抽象工厂的精神&#xff0c;就是要有abstract class&#xff08;not implement&#xff09;&#xff0c;而所有不同种类的对象&#xff0c;都是继承这个abstract class&a…...

Flink的算子列表状态的使用

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

使用 Github Actions 工作流自动部署 Github Pages

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

Xposed hook 抖音账户信息

本篇主要讲下hook获取 抖音账户的相关信息&#xff0c;直接上代码。 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月&#xff0c;TiD质量竞争力大会组委会和ECI专家委员会成功举办TiD大时段课程“度量驱动研发效能提升”与“ECI效能认知与改进论坛”。与会专家以《ECI软件研发效能度量规范》团体标准为要点&#xff0c;为企业研发效能度量和提升分享诸多实践成果与经验。 《ECI软件研…...

科技的成就(五十二)

405、微信公众平台正式上线 "1995 年 8 月 24 日&#xff0c;微软发布 Windows 95。Windows 95 极大地改进了前续系统的图形用户界面&#xff0c;首次推出了开始菜单、任务栏、最大化、最小化窗口以及关闭按钮。此外&#xff0c;Windows 95 最大程度兼容当时的 MS-DOS 和 …...

【23种设计模式】装饰器模式

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

解决IDEA中SpringBoot项目创建多个子模块时配置文件小绿叶图标异常问题

在新建子模块下创建配置文件&#xff1a; 在子模块gateway中新建的配置文件,正常情况下配置文件左侧是小树叶标识&#xff0c;而这次新建application-dev.yml是个小树叶标识&#xff0c;bootstrap.yml是个方框。 看其他方案都是在project structure中设置&#xff0c;但未显示…...

【马蹄集】—— 概率论专题

概率论专题 目录 MT2226 抽奖概率MT2227 饿饿&#xff01;饭饭&#xff01;MT2228 甜甜花的研究MT2229 赌石MT2230 square MT2226 抽奖概率 难度&#xff1a;黄金    时间限制&#xff1a;1秒    占用内存&#xff1a;128M 题目描述 小码哥正在进行抽奖&#xff0c;箱子里有…...

Spring 6整合单元测试JUnit4和JUnit5

单元测试&#xff1a;JUnit 在之前的测试方法中&#xff0c;几乎都能看到以下的两行代码&#xff1a; ApplicationContext context new ClassPathXmlApplicationContext("xxx.xml"); Xxxx xxx context.getBean(Xxxx.class);这两行代码的作用是创建Spring容器&…...

【好书推荐】深入理解现代JavaScript

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

高效协同: 打造分布式系统的三种模式

在构建分布式系统时&#xff0c;分布式协调是否总是必要选项&#xff1f;本文通过一些实际的例子讨论了这一问题&#xff0c;并通过把问题区分为是否具有单调性做为是否需要分布式协调的标准。原文: Avoiding Coordination Cost: Three Patterns for Building Efficient Distri…...

机器学习-无监督学习之聚类

文章目录 K均值聚类密度聚类&#xff08;DBSCAN&#xff09;层次聚类AGNES 算法DIANA算法 高斯混合模型聚类聚类效果的衡量指标小结 K均值聚类 步骤&#xff1a; Step1&#xff1a;随机选取样本作为初始均值向量。 Step2&#xff1a;计算样本点到各均值向量的距离&#xff0c;…...

智能垃圾桶丨悦享便捷生活

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

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…...

C++:std::is_convertible

C++标志库中提供is_convertible,可以测试一种类型是否可以转换为另一只类型: template <class From, class To> struct is_convertible; 使用举例: #include <iostream> #include <string>using namespace std;struct A { }; struct B : A { };int main…...

SciencePlots——绘制论文中的图片

文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了&#xff1a;一行…...

iPhone密码忘记了办?iPhoneUnlocker,iPhone解锁工具Aiseesoft iPhone Unlocker 高级注册版​分享

平时用 iPhone 的时候&#xff0c;难免会碰到解锁的麻烦事。比如密码忘了、人脸识别 / 指纹识别突然不灵&#xff0c;或者买了二手 iPhone 却被原来的 iCloud 账号锁住&#xff0c;这时候就需要靠谱的解锁工具来帮忙了。Aiseesoft iPhone Unlocker 就是专门解决这些问题的软件&…...

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

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

【Go语言基础【12】】指针:声明、取地址、解引用

文章目录 零、概述&#xff1a;指针 vs. 引用&#xff08;类比其他语言&#xff09;一、指针基础概念二、指针声明与初始化三、指针操作符1. &&#xff1a;取地址&#xff08;拿到内存地址&#xff09;2. *&#xff1a;解引用&#xff08;拿到值&#xff09; 四、空指针&am…...

现有的 Redis 分布式锁库(如 Redisson)提供了哪些便利?

现有的 Redis 分布式锁库&#xff08;如 Redisson&#xff09;相比于开发者自己基于 Redis 命令&#xff08;如 SETNX, EXPIRE, DEL&#xff09;手动实现分布式锁&#xff0c;提供了巨大的便利性和健壮性。主要体现在以下几个方面&#xff1a; 原子性保证 (Atomicity)&#xff…...

C++课设:简易日历程序(支持传统节假日 + 二十四节气 + 个人纪念日管理)

名人说:路漫漫其修远兮,吾将上下而求索。—— 屈原《离骚》 创作者:Code_流苏(CSDN)(一个喜欢古诗词和编程的Coder😊) 专栏介绍:《编程项目实战》 目录 一、为什么要开发一个日历程序?1. 深入理解时间算法2. 练习面向对象设计3. 学习数据结构应用二、核心算法深度解析…...

适应性Java用于现代 API:REST、GraphQL 和事件驱动

在快速发展的软件开发领域&#xff0c;REST、GraphQL 和事件驱动架构等新的 API 标准对于构建可扩展、高效的系统至关重要。Java 在现代 API 方面以其在企业应用中的稳定性而闻名&#xff0c;不断适应这些现代范式的需求。随着不断发展的生态系统&#xff0c;Java 在现代 API 方…...

鸿蒙(HarmonyOS5)实现跳一跳小游戏

下面我将介绍如何使用鸿蒙的ArkUI框架&#xff0c;实现一个简单的跳一跳小游戏。 1. 项目结构 src/main/ets/ ├── MainAbility │ ├── pages │ │ ├── Index.ets // 主页面 │ │ └── GamePage.ets // 游戏页面 │ └── model │ …...