ElasticSearch系列(四)--springboot使用ElasticsearchRestTemplate整合ElasticSearch,实现文本高亮检索

article/2025/9/20 18:58:50

前言

ElasticsearchRestTemplate是spring-data-elasticsearch项目中的一个类,和其他spring项目中的template类似。

网上的学习资料大都是基于ElasticsearchTemplate,但是ElasticsearchTemplate在未来的版本会被废除

预备知识

- 建立索引
因为是基于springboot,那就不再使用kibana进行建立索引,而是用springboot来创建.创建索引的api:
ElasticsearchRestTemplate.createIndex(实体类.class)
如,现在创建一个名为esBean的实体类

相当于建库:
@Document用于指定索引
@Field(type = FieldType.Text,analyzer = “ik_max_word”)用于指定类型

@Data
@NoArgsConstructor
@Document(indexName = "test")
public class esBean {@Idprivate int id;@Field(type = FieldType.Text,analyzer = "ik_max_word")private String name;@Field(type = FieldType.Text,analyzer = "ik_max_word")private String tags;public esBean(int id,String name,String tags){this.id=id;this.name=name;this.tags=tags;}
}

service层:

public class esService  implements IesService {@Autowiredprivate ElasticsearchRestTemplate template;@Overridepublic void create(){template.createIndex(esBean.class);}
}

像这样,就会自动建立一个名为test的索引,表结果就是esBean的成员

存储数据

需要一个持久化层的接口去继承ElasticsearchRepository,接着在service层中,依赖注入,直接调用其saveAll()方法即可,如下:

持久层:(可以在这里做一些搜索查询)

@Service
public interface esMapper extends ElasticsearchRepository<esBean,Long> {}

service层:

可以看到,saveAll,findAll这些方法是原来就有的,无需自己定义

public class esService  implements IesService {@Autowiredprivate ElasticsearchRestTemplate template;@AutowiredesMapper mapper;@Overridepublic Iterator<esBean> findAll() {return mapper.findAll().iterator();}public void create(){template.createIndex(esBean.class);}@Overridepublic void saveAll(List<esBean> list) {mapper.saveAll(list);}
}

controller层:

@AutowiredIesService iesService;@GetMapping("/init1")public String init1(){iesService.create();// id name tagsList<esBean>list=new ArrayList<>();list.add(new esBean(1,"张三锕爱","很帅,有很多人喜欢他"));list.add(new esBean(2,"李四酷狗","很帅,但是讨厌他"));list.add(new esBean(3,"王五王二爷","很丑,有是喜欢他"));list.add(new esBean(4,"张三王二婆","很帅,有没人喜欢他"));iesService.saveAll(list);return "success";}

ElasticsearchRestTemplate的基本api

SearchQuery 总的查询
BoolQueryBuilder bool查询,可在后面加上must,mustNot,should等等
MatchQueryBuilder 匹配查询
TermQueryBuilder 倒排索引查询
HighlightBuilder 高亮查询,用于设置要高亮的field
SearchHit 查询结果

实现文本高亮检索步骤

实体类:

@Data
@NoArgsConstructor
@Document(indexName = "test5")
public class esBean {@Idprivate int id;@Field(type = FieldType.Text,analyzer = "ik_max_word")private String name;@Field(type = FieldType.Text,analyzer = "ik_max_word")private String tags;public esBean(int id,String name,String tags){this.id=id;this.name=name;this.tags=tags;}
}

持久层


@Service
public interface esMapper extends ElasticsearchRepository<esBean,Long> {}

service:

public interface IesService {public Iterator<esBean> findAll();public void saveAll(List<esBean> list);public void create();public AggregatedPage testForHigh() throws IOException;
}

@Service
public class esService  implements IesService {@Autowiredprivate ElasticsearchRestTemplate template;@AutowiredesMapper mapper;@Overridepublic Iterator<esBean> findAll() {return mapper.findAll().iterator();}public void create(){template.createIndex(esBean.class);}@Overridepublic void saveAll(List<esBean> list) {mapper.saveAll(list);}public AggregatedPage  testForHigh() throws IOException {String preTag = "<font color='#dd4b39'>";//google的色值String postTag = "</font>";BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder().must(new MatchQueryBuilder("tags","很帅"));SearchQuery searchQuery=new NativeSearchQueryBuilder().   //总的查询withQuery(boolQueryBuilder).           //设置bool查询withHighlightFields(new HighlightBuilder.Field("name").preTags(preTag).postTags(postTag)).//设置高亮效果withHighlightFields(new HighlightBuilder.Field("tags").preTags(preTag).postTags(postTag)).build();AggregatedPage<esBean> ideas=template.queryForPage(searchQuery, esBean.class, new SearchResultMapper() {@Overridepublic <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {List<esBean> list = new ArrayList<>();for(SearchHit  hit:searchResponse.getHits()){//获取遍历查询结果if(searchResponse.getHits().getHits().length<=0)return null;esBean bean=new esBean();Map map=hit.getSourceAsMap();System.out.println(map);bean.setId((Integer)map.get("id"));bean.setName((String)map.get("name"));HighlightField name=hit.getHighlightFields().get("name");if(name!=null){bean.setName(name.fragments()[0].toString());   //得到高亮的结果}HighlightField tags=hit.getHighlightFields().get("tags");if(tags!=null){bean.setTags(tags.fragments()[0].toString());}list.add(bean);}if(list.size()>0)return new AggregatedPageImpl<>((List<T>)list);return null;}@Overridepublic <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {return null;}});ideas.get().forEach(model->{System.out.println(model);});return ideas;}@Overridepublic <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {return null;}});ideas.get().forEach(model->{System.out.println(model);});return ideas;}
}

controller:

@RestController
@RequestMapping("/elastic")
public class ElasticController {@AutowiredIesService iesService;@GetMapping("/init1")public String init1(){iesService.create();// id name tagsList<esBean>list=new ArrayList<>();list.add(new esBean(1,"张三锕爱","很帅,有很多人喜欢他"));list.add(new esBean(2,"李四酷狗","很帅,但是讨厌他"));list.add(new esBean(3,"王五王二爷","很丑,有是喜欢他"));list.add(new esBean(4,"张三王二婆","很帅,有没人喜欢他"));iesService.saveAll(list);return "success";}@GetMapping("/get1")public AggregatedPage get1() throws IOException {return iesService.testForHigh();}}

postman访问:

在这里插入图片描述


http://chatgpt.dhexx.cn/article/ANPlYmGe.shtml

相关文章

springBoot集成es(三)spring-data集成es与常用查询操作

接着上一篇博客&#xff0c;看下spring-data集成es的常用查询操作&#xff08;这里只写serviceImpl部分代码&#xff09;&#xff1a;ElasticsearchRepository使用QueryBuilder构造查询条件 &#xff1a;Iterable<T> search(QueryBuilder var1); 官网介绍&#xff1a;ht…

es的must_not的踩坑

文章目录 前言一、需求背景二、坑2.1 坑一2.2 坑二 总结 前言 记录下在公司做需求时must_not踩的坑 一、需求背景 要去做人才库的一个排除项&#xff1a;排除x个月面试不通过。实际上的dsl语句则对应的是must_not。且内部要包含两个元素&#xff1a;x个月、面试不通过&#x…

elasticsearch 父子文档使用must not 正确姿势

需求描述&#xff1a; 1、基于elasticsearch 父子文档进行子条件查询父文档 2、需要查询出子文档不存在的父文档 已知文档结构&#xff1a; 1、父文档clue_list 关联很多的子文档&#xff0c;我们用roam子文档做测试&#xff01; 2、roam子文档的结构 {"took" :…

Elasticsearch 的Java API使用匹配空或者是null字段

全文检索数据权限控制&#xff0c;需要根据业务权限配置&#xff1b; 本组成员包括查看自己【有些模块本来就没有分组】&#xff0c;此时需要查询groupId为null&#xff0c;但是creator为自己的数据&#xff01; 参考案例 .must(QueryBuilders.existsQuery("message&qu…

ES-3-高级查询

文章目录 1 深分页Scroll1.1 分页的查询过程1.2 Scroll查询的实现 2 delete-by-query3 ES的复合查询3.1 bool查询3.2 boosting查询 4 filter查询5 高亮查询6 聚合查询6.1 去重计数查询cardinality6.2 范围统计range6.3 统计聚合查询extended_stats 1 深分页Scroll 1.1 分页的查…

Elasticsearch嵌套查询must和mustNot

场景&#xff1a;在bug关联固件的时候将bug的数据放到固件的数据下&#xff0c;可以根据固件数据下是否包含bug数据查询出已关联和未关联的数据。 ES文档结构 目录 1.must查询此bug关联的固件 java代码 2.mustNot查询此bug未关联的固件 java代码 3.劫后余生 4.闲来…

MQ消息

AMQP协议介绍 AMQP&#xff0c;即Advanced Message Queuing Protocol&#xff0c;高级消息队列协议&#xff0c;是应用层协议的一个开放标准&#xff0c;为面向消息的中间件设计。 AMQP的主要特征是面向消息、队列、路由&#xff08;包括点对点和发布/订阅&#xff09;、可靠性…

MQ基础信息mq的简介

MQ 同步和异步通讯 微服务间通讯有同步和异步两种方式&#xff1a; 同步通讯&#xff1a;就像打电话&#xff0c;需要实时响应。 异步通讯&#xff1a;就像发邮件&#xff0c;不需要马上回复。 两种方式各有优劣&#xff0c;打电话可以立即得到响应&#xff0c;但是你却不能…

MFQ

一什么是MFQ&PPDCS&#xff1f;MFQ&PPDCS是由外部教练邰晓梅提出的一套测试分析和测试设计方法。MFQ将被测对象分层&#xff0c;针对不同层次进行测试分析和设计进行&#xff0c;使测试设计人员不会那么容易忘记一些测试的相关点&#xff08;功能交互、质量属性&#x…

MQ的了解

MQ的了解&#xff1a; 如果进行产品选型 Kafka 优点&#xff1a;吞吐量非常大&#xff0c;性能非常好&#xff0c;集群高可用。 缺点&#xff1a;会丢数据&#xff0c;功能比较单一 使用场景&#xff1a;日志分析、大数据采集 RebbitMQ 优点&#xff1a;消息可靠性高&…

多级反馈队列调度算法(MFQ)

多级反馈队列调度算法是目前公认的较好的一种进程调度算法,它能较好的满足各类进程的需要。 MFQ算法首先设置多个就绪队列。队列的优先级递减,且各队列时间片大小也不同。例如我实现的算法里,设置了3个队列,第一队列优先级>第二队列>第三队列,且后一个队列的时间片大…

从MFQ方法到需求分析

前几天看了一篇性能测试相关的文章&#xff1a;性能测试模型初探及应用方法分析&#xff0c;其中提到了MFQ分析方法。专门去查阅了MFQ相关的一些资料&#xff0c;学习了一番。 之后想起了以前看《Google的软件测试之道》这本书时&#xff0c;书中提到的一种测试分析方法&#x…

nRF24l01无线传输

模块简介&#xff1a; 它是一款工作于2.4GHZ~2.5GHZISM频段&#xff0c;带功放通信距离可达上千米&#xff0c;近距离传输速度可达2Mbps&#xff0c;具有6通道且每通道都有自己的缓冲区&#xff0c;可以同时跟不同的NFR进行通信的无线收发模块。 工作模式&#xff1a;接收模式…

C51- NRF24L01 无线串口模块

1.硬件知识 1.1 nRF24L01的引脚功能 &#xff08;IO方向是相对模块而言的&#xff09; CE&#xff1a;Chip Enable&#xff0c;芯片使能&#xff0c;在发送和接收过程中都要将这个引脚拉高。 IRQ: 低电平触发&#xff0c;当状态寄存器中 TX_DS、RX_DR 或 MAX_RT 为高时触发中断…

NRF24L01+模块实现双向通信(带ACK payload)

本文主要关于NRF24L01 2.4GHz无线模块的应用。 目录 说明模块开发的大致步骤使用方式一、单向通信二、双向通信&#xff08;有应答包(ACK payload))寄存器配置 三、星状组网 注意事项 说明 1、NRF24L01和NRF24L01的区别&#xff0c;前者支持Enhanced ShockBurst™,后者不支持…

2.4G模块NRF24L01调试经验

参照野火STM32程序调试NRF24L01成功&#xff0c;颇获喜感 nRF24L01是一款工作在2.4~2.5GHz世界通用ISM频段的单片无线收发器芯片。无线收发器包括&#xff1a;频率发生器、增强型SchockBurstTM模式控制器、功率放大器、警惕振荡器、调制器、解调器。输出功率、频道选择和协议的…

小体积、高速率的nRF24L01芯片通信模块

在选择纯硬件通信模块时&#xff0c; 面对上述问题&#xff0c;AS01提供了很好的解决办法。 AS01系列模块是工作在2.4GHz(ISM频段)的纯硬件模块。此系列基于NORDIC原装nRF24L01P芯片方案开发&#xff0c;提供多种接口形式&#xff0c;具有高空速&#xff08;最高空速可达到2…

Arduino使用NRF24L01模块进行无线通信

Arduino使用NRF24L01模块进行无线通信 前言 ​ 其实CSDN有很多关于这个无线模块的使用&#xff0c;包括Arduino的使用例程&#xff0c;但是实际自己跟着做一遍的时候还是发现了有些小问题&#xff0c;于是记录一下方便以后做其他有意思的小项目。&#xff08;Arduino的库文件…

nRF24L01--2.4G无线通信模块(1)(51单片机和51单片机通信)

作者&#xff1a;李剀 出处&#xff1a;https://www.cnblogs.com/kevin-nancy/ 或者 https://blog.csdn.net/Kevin_8_Lee/article/details/95667604 欢迎转载&#xff0c;但也请保留上面这段声明。谢谢&#xff01;&#xff08;上面两个都是我的博客&#xff0c;只是在不同平台…

STM32控制NRF24L01无线模块进行通信

一.NRF2401无线模块 1.模块介绍 功能介绍 (1)2.4Ghz 全球开放ISM 频段免许可证使 2) 最高工作速率2Mbps&#xff0c;高效GFSK调制&#xff0c;抗干扰能力强&#xff0c;特别适合工业控制场合 (3)126 频道&#xff0c;满足多点通信和跳频通信需要 (4) 内置硬件CRC 检错和点对…