Spring Boot 集成 Elasticsearch(含 ElasticsearchRestTemplate 示例)

Elasticsearch 是一個基于 Lucene 的分布式搜索服務器,具有高效的全文檢索能力。在現代應用中,尤其是需要強大搜索功能的系統中,Elasticsearch 被廣泛使用。

Spring Boot 提供了對 Elasticsearch 的集成支持,使得開發者可以輕松地將 Elasticsearch 集成到 Spring Boot 應用中,實現高效的搜索、分析等功能。本文將詳細介紹如何在 Spring Boot 中集成 Elasticsearch,并展示一些基本的使用示例以及通過 ElasticsearchRestTemplate 實現的高級功能。

一、準備工作

1. 安裝 Elasticsearch

你可以通過以下方式安裝 Elasticsearch:

  • 使用 Docker 安裝
docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:8.11.3
  • 直接下載安裝包:Elasticsearch 下載頁面

確保 Elasticsearch 成功啟動后,可以通過瀏覽器訪問 http://localhost:9200 查看其狀態信息。


二、創建 Spring Boot 項目

使用 Spring Initializr 創建一個 Spring Boot 項目,選擇以下依賴:

  • Spring Web
  • Spring Data Elasticsearch

或者手動在 pom.xml 中添加如下依賴(適用于 Maven 項目):

<dependencies><!-- Spring Boot Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><!-- Spring Boot Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Data Elasticsearch --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><!-- Lombok(可選) --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency>
</dependencies>

三、配置 Elasticsearch

application.ymlapplication.properties 中配置 Elasticsearch 連接信息:

spring:elasticsearch:rest:uris: http://localhost:9200

如果你使用的是較老版本的 Spring Boot,可能需要手動配置 RestHighLevelClient,但在新版本中已默認使用 ElasticsearchRestTemplateRestClient


四、定義實體類

我們先定義一個簡單的實體類,并使用注解來映射 Elasticsearch 索引結構。

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;@Document(indexName = "blog-post", shards = 1)
public class BlogPost {@Idprivate String id;@Field(type = FieldType.Text, analyzer = "ik_max_word")private String title;@Field(type = FieldType.Text, analyzer = "ik_max_word")private String content;// 構造方法、getter/setter 省略
}

注意:如果使用中文分詞,建議使用 ik-analyzer 插件,在 Elasticsearch 中安裝后指定 analyzer


五、定義 Repository 接口

Spring Data 提供了 ElasticsearchRepository 接口,我們可以繼承它來操作文檔。

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;public interface BlogPostRepository extends ElasticsearchRepository<BlogPost, String> {
}

六、編寫 Service 層

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.Optional;@Service
public class BlogPostService {@Autowiredprivate BlogPostRepository blogPostRepository;public BlogPost save(BlogPost blogPost) {return blogPostRepository.save(blogPost);}public Optional<BlogPost> findById(String id) {return blogPostRepository.findById(id);}public Iterable<BlogPost> findAll() {return blogPostRepository.findAll();}public void deleteById(String id) {blogPostRepository.deleteById(id);}public List<BlogPost> searchByTitle(String title) {return blogPostRepository.findByTitle(title);}
}

七、編寫 Controller 層

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/blog-posts")
public class BlogPostController {@Autowiredprivate BlogPostService blogPostService;@PostMappingpublic BlogPost create(@RequestBody BlogPost blogPost) {return blogPostService.save(blogPost);}@GetMapping("/{id}")public BlogPost get(@PathVariable String id) {return blogPostService.findById(id).orElse(null);}@GetMappingpublic Iterable<BlogPost> getAll() {return blogPostService.findAll();}@DeleteMapping("/{id}")public void delete(@PathVariable String id) {blogPostService.deleteById(id);}@GetMapping("/search")public List<BlogPost> search(@RequestParam String title) {return blogPostService.searchByTitle(title);}
}

八、補充內容:使用 ElasticsearchRestTemplate

除了使用 Repository,我們還可以通過 ElasticsearchRestTemplate 來執行更復雜的查詢、聚合、高亮等操作。

1. 注入 ElasticsearchRestTemplate

@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;

2. 構建基本查詢(Match 查詢)

import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;public List<BlogPost> searchByTitleWithTemplate(String keyword) {Criteria criteria = new Criteria("title").is(keyword);CriteriaQuery query = new CriteriaQuery(criteria);SearchHits<BlogPost> hits = elasticsearchRestTemplate.search(query, BlogPost.class);return hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
}

3. 使用 NativeSearchQueryBuilder 構建復雜查詢

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.MatchQueryBuilder;import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;public List<BlogPost> searchByContentWithMatchQuery(String keyword) {MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("content", keyword);SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQueryBuilder).build();SearchHits<BlogPost> hits = elasticsearchRestTemplate.search(searchQuery, BlogPost.class);return hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
}

4. 聚合查詢(Aggregation)

import org.elasticsearch.index.aggregation.AggregationBuilders;
import org.elasticsearch.index.aggregation.bucket.terms.TermsAggregationBuilder;public void aggregateKeywordsInTitle() {TermsAggregationBuilder aggregation = AggregationBuilders.terms("keywords").field("title.keyword") // 注意字段類型應為 keyword.size(10);SearchQuery searchQuery = new NativeSearchQueryBuilder().withAggregations(aggregation).build();SearchHits<BlogPost> hits = elasticsearchRestTemplate.search(searchQuery, BlogPost.class);Terms keywordsAgg = hits.getAggregations().get("keywords");for (Terms.Bucket entry : keywordsAgg.getBuckets()) {System.out.println(entry.getKey() + ":" + entry.getDocCount());}
}

5. 高亮顯示匹配內容

import org.elasticsearch.index.highlight.HighlightBuilder;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;public List<BlogPost> searchWithHighlight(String keyword) {HighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.field("content"); // 對 content 字段進行高亮highlightBuilder.preTags("<strong>").postTags("</strong>");MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("content", keyword);SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery).withHighlightBuilder(highlightBuilder).build();SearchHits<BlogPost> hits = elasticsearchRestTemplate.search(searchQuery, BlogPost.class);return hits.stream().map(hit -> {Map<String, List<String>> highlightFields = hit.getHighlightFields();if (highlightFields.containsKey("content")) {String highlightedContent = String.join("...", highlightFields.get("content"));hit.getContent().setContent(highlightedContent); // 替換內容為高亮版本}return hit.getContent();}).collect(Collectors.toList());
}

6. 分頁查詢

public List<BlogPost> searchWithPagination(String keyword, int page, int size) {MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", keyword);SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery).withPageable(PageRequest.of(page, size)).build();SearchHits<BlogPost> hits = elasticsearchRestTemplate.search(searchQuery, BlogPost.class);return hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
}

九、測試 API

你可以使用 Postman 或 curl 測試以下接口:

  • POST /api/blog-posts:創建一篇博客
  • GET /api/blog-posts/{id}:獲取某篇博客
  • GET /api/blog-posts:獲取所有博客
  • DELETE /api/blog-posts/{id}:刪除博客
  • GET /api/blog-posts/search?title=xxx:按標題搜索博客
  • 更多通過 ElasticsearchRestTemplate 支持的高級查詢也可以通過新增接口調用。

十、總結

本文詳細介紹了如何在 Spring Boot 項目中集成 Elasticsearch,并實現了基本的增刪改查操作。同時,通過 ElasticsearchRestTemplate 展示了構建復雜查詢、聚合、高亮、分頁等高級功能的方式。

通過 Spring Data Elasticsearch 提供的抽象,我們可以非常方便地進行數據持久化和檢索。而 ElasticsearchRestTemplate 則為我們提供了更靈活的底層控制能力,非常適合用于構建企業級搜索功能。


參考資料

  • Spring Data Elasticsearch 官方文檔
  • Elasticsearch 官網
  • IK Analyzer GitHub

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/87529.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/87529.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/87529.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

CMake實踐:指定gcc版本編譯和交叉編譯

目錄 1.指定gcc版本編譯 1.1.通過CMake參數來實現 1.2.使用 RPATH/RUNPATH 直接指定庫路徑 1.3.使用符號鏈接和 LD_LIBRARY_PATH 1.4.使用 wrapper 腳本封裝 LD_LIBRARY_PATH 2.交叉編譯 2.1.基本用法 2.2.工具鏈文件關鍵配置 2.3.多平臺工具鏈示例 2.4.注意事項 2.…

詳解鴻蒙Next倉頡開發語言中的全屏模式

大家好&#xff0c;今天跟大家分享一下倉頡開發語言中的全屏模式。 和ArkTS一樣&#xff0c;倉頡的新建項目默認是非全屏模式的&#xff0c;如果你的應用顏色比較豐富&#xff0c;就會發現屏幕上方和底部的留白&#xff0c;這是應用自動避讓了屏幕上方攝像頭區域和底部的導航條…

LoRA 淺析

1. 核心思想 LoRA 是一種參數高效的微調方法&#xff0c;旨在減少微調大型語言模型 (LLMs) 所需的計算資源和存儲空間。其核心思想是&#xff1a; 凍結預訓練模型權重&#xff1a; 在微調過程中&#xff0c;保持預訓練 LLM 的原始權重不變。引入低秩矩陣&#xff1a; 對于 LL…

軟件范式正在經歷第三次革命

核心主題&#xff1a;軟件范式正在經歷第三次根本性革命&#xff08;軟件3.0&#xff09;&#xff0c;其核心是“智能體”&#xff08;Agent&#xff09;&#xff0c;未來十年將是“智能體的十年”。 邏輯模塊解析&#xff1a; 軟件的三次重生革命 軟件1.0&#xff1a; 傳統編…

JavaScript 變量與運算符全面解析:從基礎到高級應用

昨天學長說可以放緩一下學習進度,剛好最近期末復習也不是很緊張,所以來重新復習一下js的一些知識點。 一&#xff1a;變量 &#xff08;1&#xff09;變量聲明 來簡單看一下變量的一些知識點。首先是變量聲明&#xff1a;變量聲明盡量使用數組字母下劃線 來舉幾個例子&#x…

移動語義對性能優化的具體示例

前言 本文章對比了&#xff1a;小中大字符串在普通傳值、傳值移動、傳左值引用、傳右值引用、模板完美轉發、內聯版本等多種測試&#xff0c;對比各個方式的性能優異&#xff1a; 測試代碼1 #include <iostream> #include <string> #include <chrono> #incl…

C/C++ 和 OpenCV 來制作一個能與人對弈的實體棋盤機器人

項目核心架構 整個系統可以分為四個主要模塊&#xff1a; 視覺感知模塊 (Vision Perception Module): 任務: 使用攝像頭“看懂”棋盤。工具: C, OpenCV。功能: 校準攝像頭、檢測棋盤邊界、進行透視變換、分割 64 個棋盤格、識別每個格子上的棋子、檢測人類玩家的走法。 決策模…

SpringBoot擴展——日志管理!

Spring Boot擴展 在Spring Boot中可以集成第三方的框架如MyBatis、MyBatis-Plus和RabbitMQ等統稱為擴展。每一個擴展會封裝成一個集成&#xff0c;即Spring Boot的starter&#xff08;依賴組件&#xff09;。starter是一種非常重要的機制&#xff0c;不需要煩瑣的配置&#xf…

【JSON-To-Video】AI智能體開發:為視頻圖片元素添加動效(滑入、旋轉、滑出),附代碼

各位朋友們&#xff0c;大家好&#xff01; 今天要教大家如何在 JSON - To - Video 中為視頻內圖片元素添加滑入、旋轉、滑出的動效。 如果您還不會封裝制作自己的【視頻工具插件】&#xff0c;歡迎查看之前的教程&#xff01; AI智能體平臺&#xff0c;如何封裝自定義短視頻…

Spring Boot(九十二):Spring Boot實現連接不上數據庫就重啟服務

場景: 在線上部署時,若服務器因斷電等原因意外重啟,項目及其依賴的數據庫服務通常需要配置為自動啟動。此時,如果數據庫服務啟動較慢或失敗,Spring Boot 項目會因無法建立數據庫連接而啟動失敗。 需求: 為確保項目啟動成功,需要讓 Spring Boot 項目等待數據庫服務完全就…

Debian配置Redis主從、哨兵

前言 Redis的下載安裝可參考Centos安裝配置Redis6.x&#xff0c;Centos和Debian的步驟基本類似&#xff0c;或自行在網上搜索相關資料 注意&#xff1a;遠程連接需放開相應端口 主從 搭建一個一主二從的主從模式 處理conf文件 #進入redis所在目錄 cd /tools/redis/redis6 …

虛實交融:數字孿生如何重塑交通與公路勘察設計的未來

當每一條道路、每一座橋梁、每一盞信號燈都在數字世界獲得“永生副本”&#xff0c;交通系統從被動響應邁入主動預演的紀元 一、數字孿生的核心定義&#xff1a;超越鏡像的動態認知引擎 數字孿生&#xff08;Digital Twin&#xff09;并非簡單的三維可視化模型&#xff0c;而是…

vector模擬實現中的迭代器失效問題

首先來看一組代碼&#xff1a; iterator insert(iterator pos, const T& x) {// 擴容if (_finish _end_of_storage){size_t len pos - _stare;reserve(capacity() 0 ? 4 : capacity() * 2);pos _stare len;}iterator end _finish - 1;while (end > pos){*(end…

java 設計模式_行為型_22模板模式

22.模板模式 模板方法&#xff08;Template Method&#xff09;作為Java的設計模式之一&#xff0c;一個詞概括其優勢特點那就是&#xff1a;抽象步驟 首先我們應該抽出共通的東西做一個父類&#xff08;Base類&#xff09;&#xff0c;其次具體的蛋糕制作由子類進一步實現&…

隨記:在springboot中websocket的使用

我現在有兩種方法 第一種&#xff1a;使用java封裝的這個包下的javax.websocket.* 先配置這個配置類 import com.alibaba.nacos.common.utils.CollectionUtils; import org.springframework.stereotype.Component;import javax.websocket.HandshakeResponse; import javax.w…

技術文章大綱:SpringBoot自動化部署實戰

技術文章大綱&#xff1a;SpringBoot自動化部署實戰 概述 自動化部署的背景與意義SpringBoot在現代化部署中的優勢常見自動化部署工具與方案概覽&#xff08;Jenkins、Docker、K8s等&#xff09; 環境準備 基礎工具要求&#xff1a;JDK、Maven/Gradle、Git服務器環境配置&a…

FastAdmin按鈕類功能全解析 class 屬性定義不同的交互行為

在 FastAdmin 中&#xff0c;超鏈接的 class 屬性用于定義不同的交互行為和樣式。以下是常見 class 配置的用途和區別&#xff1a; btn-dialog 用于觸發彈出對話框行為。點擊帶有此 class 的鏈接或按鈕時&#xff0c;FastAdmin 會自動加載指定的 URL 內容并在模態框中顯示。通…

python3字典對象實現解析

文章目錄 前言Raymond的方案字典結構字典創建字典插入插入空字典PyDictKeysObject的創建設置索引存儲entry 插入非空字典調整大小字典查找聯合字典插入 字典查詢字典刪除 前言 本來以為python字典的實現就是一個哈希表的普通實現&#xff0c;所以在學習基本類型時沒去仔細研究…

Word2Vec介紹

前言 當今的大語言模型非常智能&#xff0c;但是你有沒有想過這些事情&#xff1a; 機器是怎么理解“國王”和“王后”之間的關系&#xff1f; “貓”和“狗”是怎么在 AI 中“相似以及區分”的&#xff1f; 文本又是怎么變成模型能讀懂的數字&#xff1f; 這一切&#xf…

Rsync+sersync實現數據實時同步(小白的“升級打怪”成長之路)

目錄 一、rsync部署 push推數據 1、編寫rsync配置文件 2、備份測試 3、檢驗結果 二、rsyncsersync 實現數據實時同步 1、安裝sersync服務 2、檢驗結果 pull拉取數據 1、編寫rsync配置文件 2、檢驗結果 三、腳本編寫 1、客戶端腳本編寫 2、服務器腳本編寫 一、rsy…