Spring Boot整合实战:Elasticsearch集成与全文搜索功能完整实现指南
Spring Boot整合实战Elasticsearch集成与全文搜索功能完整实现指南前言一、版本兼容性说明关键二、整合实现完整流程图三、第一步Maven 核心依赖四、第二步application.yml 配置连接五、第三步创建 ES 实体类索引映射六、第四步创建 Repository 接口DAO层七、第五步实现基础功能Service层7.1 基础增删改查八、第六步实现**全文搜索**核心功能8.1 全文搜索 分页 高亮九、第七步编写 Controller 接口十、功能测试可直接运行十一、搜索功能执行流程图核心十二、常见问题与解决方案十三、总结The Begin点点关注收藏不迷路前言在现代微服务、电商、博客、日志系统中全文搜索已经成为标配功能。Spring Boot 作为主流开发框架结合 Elasticsearch 可快速实现高性能、分布式、近实时的搜索服务。很多新手在整合过程中会遇到版本不兼容、连接失败、查询不生效、实体映射错误等问题。本文基于Spring Boot 3.x Elasticsearch 8.x最新稳定版提供从零到一的完整集成教程包含环境搭建、实体映射、CRUD、高级搜索、高亮显示全程流程图可直接运行的代码让你快速落地搜索功能。一、版本兼容性说明关键Spring Data Elasticsearch 与 Elasticsearch 版本必须严格对应否则启动报错。本文使用稳定兼容版本Spring Boot 3.2.0Spring Data Elasticsearch 5.2.xElasticsearch 8.8.x注意ES 8.x 默认开启 SSL 安全认证学习环境可关闭简化配置。二、整合实现完整流程图创建SpringBoot项目引入Maven依赖配置application.yml创建ES实体类索引映射创建Repository接口实现基础CRUD实现全文搜索/高亮/分页接口测试功能验证三、第一步Maven 核心依赖创建 Spring Boot 项目在pom.xml添加 ES 依赖!-- Spring Boot Elasticsearch 核心启动器 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-elasticsearch/artifactId/dependency!-- Lombok 简化代码 --dependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdoptionaltrue/optional/dependency四、第二步application.yml 配置连接重点ES 8.x 需要关闭 ssl、账号密码、验证。spring:elasticsearch:uris:http://localhost:9200# ES地址username:elastic# 默认账号ES8开启password:123456# 密码ssl:enabled:false# 关闭SSL五、第三步创建 ES 实体类索引映射使用Document、Field注解自动创建索引与映射。importlombok.Data;importorg.springframework.data.annotation.Id;importorg.springframework.data.elasticsearch.annotations.Document;importorg.springframework.data.elasticsearch.annotations.Field;importorg.springframework.data.elasticsearch.annotations.FieldType;/** * 文章实体类 * indexName: 索引名称自动创建 */DataDocument(indexNamearticle_index)publicclassArticle{IdprivateLongid;// 标题全文检索使用IK分词器Field(typeFieldType.Text,analyzerik_max_word,searchAnalyzerik_smart)privateStringtitle;// 分类精准匹配 keywordField(typeFieldType.Keyword)privateStringcategory;// 内容大文本搜索Field(typeFieldType.Text,analyzerik_max_word)privateStringcontent;// 时间Field(typeFieldType.Date)privateStringcreateTime;}六、第四步创建 Repository 接口DAO层继承ElasticsearchRepository直接拥有CRUD、分页、排序能力。importorg.springframework.data.elasticsearch.repository.ElasticsearchRepository;importorg.springframework.stereotype.Repository;RepositorypublicinterfaceArticleRepositoryextendsElasticsearchRepositoryArticle,Long{// 自定义方法根据标题搜索ListArticlefindByTitle(Stringtitle);}七、第五步实现基础功能Service层7.1 基础增删改查importlombok.RequiredArgsConstructor;importorg.springframework.stereotype.Service;importjava.util.Optional;ServiceRequiredArgsConstructorpublicclassArticleService{privatefinalArticleRepositoryrepository;// 1. 新增/修改文档publicArticlesave(Articlearticle){returnrepository.save(article);}// 2. 根据ID查询publicOptionalArticlegetById(Longid){returnrepository.findById(id);}// 3. 查询全部publicIterableArticlegetAll(){returnrepository.findAll();}// 4. 删除publicvoiddelete(Longid){repository.deleteById(id);}}八、第六步实现全文搜索核心功能使用ElasticsearchRestTemplate实现复杂搜索、分页、高亮、多条件匹配。8.1 全文搜索 分页 高亮importorg.springframework.data.domain.PageRequest;importorg.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;importorg.springframework.data.elasticsearch.core.SearchHit;importorg.springframework.data.elasticsearch.core.SearchHits;importorg.springframework.data.elasticsearch.core.query.NativeSearchQuery;importorg.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;importorg.springframework.stereotype.Service;importjava.util.List;importstaticorg.elasticsearch.index.query.QueryBuilders.multiMatchQuery;importstaticorg.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder.field;ServiceRequiredArgsConstructorpublicclassSearchService{privatefinalElasticsearchRestTemplatetemplate;/** * 全文搜索关键词匹配 标题内容 * 高亮显示 分页 */publicListArticlesearch(Stringkeyword,intpage,intsize){// 1. 构建查询多字段匹配NativeSearchQueryquerynewNativeSearchQueryBuilder().withQuery(multiMatchQuery(keyword,title,content))// 2. 高亮配置.withHighlightFields(field(title).preTags(span stylecolor:red).postTags(/span),field(content).preTags(span stylecolor:red).postTags(/span))// 3. 分页.withPageable(PageRequest.of(page,size)).build();// 4. 执行查询SearchHitsArticlesearchHitstemplate.search(query,Article.class);// 5. 解析结果包含高亮returnsearchHits.stream().map(hit-{Articlearticlehit.getContent();// 替换高亮字段if(hit.getHighlightFields().containsKey(title)){article.setTitle(hit.getHighlightFields().get(title).get(0));}returnarticle;}).toList();}}九、第七步编写 Controller 接口importlombok.RequiredArgsConstructor;importorg.springframework.web.bind.annotation.*;importjava.util.List;RestControllerRequestMapping(/es)RequiredArgsConstructorpublicclassEsController{privatefinalArticleServicearticleService;privatefinalSearchServicesearchService;// 新增文章PostMapping(/save)publicArticlesave(RequestBodyArticlearticle){returnarticleService.save(article);}// 全文搜索GetMapping(/search)publicListArticlesearch(RequestParamStringkeyword,RequestParam(defaultValue0)intpage,RequestParam(defaultValue10)intsize){returnsearchService.search(keyword,page,size);}// 根据ID查询GetMapping(/{id})publicArticlegetById(PathVariableLongid){returnarticleService.getById(id).orElse(null);}}十、功能测试可直接运行启动 Elasticsearch启动 Spring Boot 项目调用接口新增POST localhost:8080/es/save搜索GET localhost:8080/es/search?keywordSpringBoot返回高亮效果示例{id:1,title:span stylecolor:redSpringBoot/span整合ES教程,category:技术,content:全文检索...}十一、搜索功能执行流程图核心前端输入关键词Controller接收请求Service构建查询条件Template发送请求到ESES倒排索引检索返回匹配文档高亮解析结果封装VO返回前端展示十二、常见问题与解决方案连接失败检查 ES 地址、端口、关闭 ssl自动创建索引失败检查实体Document注解搜索不到数据检查分词器是否一致检查字段类型 text / keywordES 8.x 安全认证报错关闭 ssl / 输入正确账号密码十三、总结Spring Boot 整合 Elasticsearch 非常简单核心步骤只有4步引入依赖配置连接定义实体映射使用 Repository / Template 实现搜索本文实现了企业级最常用功能自动创建索引基础CRUD全文检索高亮显示分页查询多字段匹配完全满足博客、电商、商城、后台管理系统的搜索需求。The End点点关注收藏不迷路