Spring Boot 使用 ElasticSearch

第一步,開啟本地的 ElasticSearch

啟動 elasticSearch.bat

npm run start (head 插件)

第二步,在 Spring Boot 項目中引入依賴

        <dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.6.1</version></dependency>

第三步,配置 yml 和 配置類

# ES
elasticsearch:host: 127.0.0.1port: 9200username:  # 若 ES 無賬號密碼,可不填password:  # 若 ES 無賬號密碼,可不填connectTimeout: 5000   # 連接超時(毫秒)socketTimeout: 30000   # 讀寫超時(毫秒)maxConnTotal: 100      # 最大連接數maxConnPerRoute: 10    # 單路由最大連接數
package com.wf.config;import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class ElasticsearchConfig {@Value("${elasticsearch.host}")private String host;@Value("${elasticsearch.port}")private int port;@Value("${elasticsearch.username}")private String username;@Value("${elasticsearch.password}")private String password;@Value("${elasticsearch.connectTimeout}")private int connectTimeout;@Value("${elasticsearch.socketTimeout}")private int socketTimeout;@Value("${elasticsearch.maxConnTotal}")private int maxConnTotal;@Value("${elasticsearch.maxConnPerRoute}")private int maxConnPerRoute;@Beanpublic RestHighLevelClient restHighLevelClient() {// 構建 RestClientRestClientBuilder builder = RestClient.builder(new HttpHost(host, port, "http")).setRequestConfigCallback(requestConfigBuilder -> {requestConfigBuilder.setConnectTimeout(connectTimeout);requestConfigBuilder.setSocketTimeout(socketTimeout);return requestConfigBuilder;}).setHttpClientConfigCallback(httpClientBuilder -> {httpClientBuilder.setMaxConnTotal(maxConnTotal);httpClientBuilder.setMaxConnPerRoute(maxConnPerRoute);return httpClientBuilder;});return new RestHighLevelClient(builder);}
}

?第四步,實現實體類

package com.wf.dao.ESPojo;import lombok.Data;@Data
public class ESArticle {private String id;          // ES 文檔 IDprivate String title;       // 標題(測試 IK 分詞)private String content;     // 內容(測試 IK 分詞)private Long createTime;    // 在 ES 中的時間private String summary;//概述private Integer viewCounts;//瀏覽次數private String author;//作者
}

第五步,實現 Service

package com.wf.service;import com.alibaba.fastjson.JSON;
import com.wf.dao.ESPojo.ESArticle;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;@Service
public class ArticleEsService {@Resourceprivate RestHighLevelClient restHighLevelClient;private static final String INDEX_NAME = "article_index"; // 索引名//ik 分詞器public List<ESArticle> searchByKeyword(String keyword) throws IOException {SearchRequest request = new SearchRequest(INDEX_NAME);SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();// 構建 match 查詢:默認對 "title" 和 "content" 分詞搜索(可指定字段)MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("title", keyword).analyzer("ik_max_word"); // 明確指定分詞器(或依賴 mapping 配置)sourceBuilder.query(matchQuery);request.source(sourceBuilder);SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);// 解析結果List<ESArticle> result = new ArrayList<>();for (SearchHit hit : response.getHits().getHits()) {result.add(JSON.parseObject(hit.getSourceAsString(), ESArticle.class));}return result;}// 創建索引(含 IK 分詞配置)public boolean createIndex() throws IOException {CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);// 配置 mapping(指定 IK 分詞)XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("properties")// title 字段:索引用 ik_max_word,搜索用 ik_smart.startObject("title").field("type", "text").field("analyzer", "ik_max_word").field("search_analyzer", "ik_smart").endObject()// content 字段:同上.startObject("content").field("type", "text").field("analyzer", "ik_max_word").field("search_analyzer", "ik_smart").endObject()// summary 概述字段.startObject("content").field("type", "text").field("analyzer", "ik_max_word").field("search_analyzer", "ik_smart").endObject()// author.startObject("author").field("type","text").field("analyzer","ik_max_word").field("search_analyzer","ik_smart").endObject()// createTime 字段.startObject("createTime").field("type", "long").endObject().endObject().endObject();request.mapping(String.valueOf(mapping));// 執行創建CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);return response.isAcknowledged();}// 判斷索引是否存在public boolean existsIndex() throws IOException {IndicesExistsRequest request = new IndicesExistsRequest(INDEX_NAME);
//        return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);return true;}// 刪除索引public boolean deleteIndex() throws IOException {DeleteIndexRequest request = new DeleteIndexRequest(INDEX_NAME);return restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT).isAcknowledged();}// 新增文檔public String addDocument(ESArticle article) throws IOException {IndexRequest request = new IndexRequest(INDEX_NAME).id(article.getId()) // 自定義 ID,若不填則 ES 自動生成.source(JSON.toJSONString(article), XContentType.JSON);IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);return response.getId(); // 返回 ES 生成的 ID(若自定義則和入參一致)}// 修改文檔(根據 ID 更新)public boolean updateDocument(ESArticle article) throws IOException {UpdateRequest request = new UpdateRequest(INDEX_NAME, article.getId()).doc(JSON.toJSONString(article), XContentType.JSON);UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);return response.getResult() != null;}// 刪除文檔(根據 ID 刪除)public boolean deleteDocument(String docId) throws IOException {DeleteRequest request = new DeleteRequest(INDEX_NAME, docId);DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);return response.getResult() != null;}// 查詢文檔(根據 ID 查詢)public ESArticle getDocument(String docId) throws IOException {GetRequest request = new GetRequest(INDEX_NAME, docId);GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);if (response.isExists()) {return JSON.parseObject(response.getSourceAsString(), ESArticle.class);}return null;}
}

第六步,測試

    @Resourceprivate ArticleEsService articleEsService;// 測試創建索引@Testvoid testCreateIndex() throws IOException {boolean success = articleEsService.createIndex();System.out.println("創建索引結果:" + success); // 期望 true}// 測試新增文檔@Testvoid testAddDocument() throws IOException {ESArticle article = new ESArticle();article.setId("1");article.setTitle("Spring Boot 集成 Elasticsearch 7.6.1");article.setContent("詳細講解如何在 Spring Boot 中使用 Elasticsearch,包含 IK 分詞驗證...");article.setCreateTime(System.currentTimeMillis());String docId = articleEsService.addDocument(article);System.out.println("新增文檔 ID:" + docId); // 期望 "1"}// 測試分詞查詢(驗證 IK)@Testvoid testSearchByKeyword() throws IOException {List<ESArticle> articles = articleEsService.searchByKeyword("Spring Boot");System.out.println("查詢結果:" + articles.size()); // 期望 1articles.forEach(System.out::println);}

使用 head 查看創建情況

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

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

相關文章

軟件開發的“中庸之道”:因勢而為,心中有數

【軟件工程】軟件開發的“中庸之道”&#xff1a;因勢而為&#xff0c;心中有數 在軟件開發的方法論討論中&#xff0c;我們常常陷入非此即彼的二元對立&#xff1a;要么追求極致的規范化和流程化&#xff0c;嚴格遵循軟件工程的各項標準&#xff1b;要么完全摒棄方法論&#x…

Go和Elixir極簡HTTP服務對比

Go 和 Elixir 都是我非常喜歡的編程語言&#xff0c;這次來對比下它們實現一個原生極簡 HTTP 服務的過程。 Go 語言標準庫自帶了網絡服務庫&#xff0c;只需要簡單幾行代碼就可以實現一個網絡服務&#xff0c;這也是一開始它吸引我的一個方面。而 Elixir 標準庫本身沒有網絡服…

為何要學習Objective-C?從環境搭建開始

目錄 前言 Swift時代為何還要學Objective-C&#xff1f; 開發環境搭建 1. 安裝Xcode 2. 創建第一個Command Line Tool項目 初識Objective-C代碼 編寫"Hello, Objective-C!" 編譯運行程序 為什么Objective-C中的NSLog和NSString前面都有"NS"前綴&a…

ubuntu18.04安裝 gcc 9以及2019版本tbb

一、安裝gcc 9 ubuntu18.04默認是用的gcc7.5 sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt update sudo apt-get install gcc-9 g-9 下面是配置優先用哪個版本的gcc和g &#xff0c;后面帶的值越大越優先用誰&#xff0c;并且配置完全局生效不僅僅是在當…

JdbcUtils的三個版本以及sql注入問題

JDBC的工具類 1.0版本 JDBC的工具類 2.0版本&#xff08;智能一些&#xff09;&#xff0c;編寫properties屬性文件&#xff0c;程序就可以讀取屬性文件 JDBC的工具類 3.0版本&#xff0c;加入連接池對象 我們封裝jdbc工具類是為了減少代碼重復&#xff0c;方便開發&#xff0…

AS32系列MCU芯片I2C模塊性能解析與調試

國科安芯推出的AS32X601內置的I2C模塊提供了符合工業標準的兩線串行制接口&#xff0c;可用于MCU和外部IIC設備的通訊。IIC總線使用兩條串行線&#xff1a;串行數據線SDA和串行時鐘線SCL。 IIC接口模塊實現了IIC協議的標準模式和快速模式&#xff0c;支持多主機IIC總線架構。其…

釘釘小程序開發實戰:打造一個簡約風格的登錄頁面

在上一篇文章中&#xff0c;我們已經介紹了如何搭建釘釘小程序的基礎環境&#xff0c;并完成了項目的初始化配置。本文將繼續深入&#xff0c;手把手帶你實現一個簡約風格的登錄頁面&#xff0c;這是大多數企業級應用不可或缺的一部分。 釘釘小程序基于前端 Web 技術棧&#x…

論文研讀2-1:多GNSS雙歷元純相位定位-模型建立與誤差分析

后續文章: 論文研讀2-2&#xff1a;多GNSS雙歷元純相位定位-固定模糊度精度增益 論文研讀2-3&#xff1a;多GNSS雙歷元純相位定位-定位精度分析 僅相位定位中的模糊度解算問題 在衛星導航定位中&#xff0c;載波相位測量是實現高精度定位的基礎&#xff0c;但如果僅使用相位測…

Python----OpenCV(圖像増強——圖像平滑、均值濾波、高斯濾波、中值濾波、雙邊濾波)

Python----計算機視覺處理&#xff08;Opencv&#xff1a;圖像噪點消除&#xff1a;濾波算法&#xff0c;噪點消除&#xff09; 一、圖像平滑 圖像平滑處理&#xff08;Smoothing Images&#xff09;&#xff0c;也稱為圖像模糊處理、圖像濾波&#xff08;Images Filtering&am…

筆記:使用EasyExcel導入csv文件出現編碼問題,導致導入數據全為null的解決方法

筆記&#xff1a;使用EasyExcel導入csv文件出現編碼問題&#xff0c;導致導入數據全為null的解決方法 通常情況下&#xff0c;我們使用excel導入&#xff0c;但是部分情況下或者領導要求&#xff0c;我們需要使用csv導入文件&#xff0c;但是csv文件模板下載之后會變成系統當前…

NL2SQL(Natural Language to SQL)優化之道:提升準確率與復雜查詢能力

自然語言 → SQL 的轉譯&#xff08;NL2SQL&#xff09;技術&#xff0c;是讓非技術用戶與數據庫“對話”的橋梁。而在實際應用中&#xff0c;我們不僅需要“能轉”&#xff0c;更要“轉得準、轉得全、轉得快”。 一、什么是 NL2SQL&#xff1f; NL2SQL&#xff08;Natural La…

java中map的循環方式

什么是Map集合&#xff1f; Map是Java中的一個接口&#xff0c;它用于存儲鍵-值對&#xff0c;并且鍵和值都可以是任意對象。它是Java集合框架中的一部分&#xff0c;并提供了一些方法來操作和訪問Map中的元素。 Map中的每個鍵都是唯一的&#xff0c;這意味著不能使用相同的鍵…

python學習筆記(深度學習)

文章目錄 1、概述2、學習內容2.1、pytorch 常見語法2.1.1、sum2.1.2、廣播機制2.1.3、張量2.1.4、DataLoader 2.2、普通語法2.2.1、迭代器 1、概述 本篇博客用來記錄&#xff0c;在深度學習過程中&#xff0c;常用的 python 語法內容 2、學習內容 2.1、pytorch 常見語法 2.…

力扣網C語言編程題:搜索二維矩陣(右上角->左下角解法)

一. 簡介 上一篇文章關于"在二維數組中查找某個元素"的問題&#xff0c;提供了兩種解題思路&#xff0c;文章如下&#xff1a; 力扣網C語言編程題&#xff1a;搜索二維矩陣的普通解法與二分查找法-CSDN博客 本文提供第三種解題思路&#xff1a;從左下角->右上角…

AI大模型流式輸出,OkHttp Log攔截打印方案

背景&#xff1a; 使用okhttp框架進行網絡訪問時&#xff0c;一般會使用 HttpLoggingInterceptor 打印請求和響應的log。在使用okhttp訪問AI大模型時&#xff0c;如果選擇流式輸出&#xff0c;那么響應的body數據使用的SSE技術&#xff0c;服務異步發送大模型生成的增量token&…

看數據世界的歷史:全面梳理從關系庫、大數據到AI時代的數據發展及展望

序章 在數據庫不斷發展的時代里&#xff0c;我們看到了關系型數據庫&#xff08;RDB&#xff09;在一次次的數據演變過程中的占據王位&#xff0c;捍衛了勝利&#xff0c;像一個王朝更替下的“王權”的故事&#xff0c;精彩有趣。 本篇就來探討下數據庫的發展興衰史&#xff0…

元宇宙與人工智能的融合:從虛擬世界到智能生態的IT新革命

文章目錄 引言&#xff1a;前沿技術重塑數字交互體驗一、元宇宙與AI融合的本質&#xff1a;虛擬空間與智能交互的交匯元宇宙賦能AI&#xff1a;AI賦能元宇宙&#xff1a; 二、元宇宙與AI融合的演進&#xff1a;從概念到產業熱潮三、核心技術&#xff1a;元宇宙與AI融合的基石與…

問卷調查[mqtt dht]

任務 this code uses esp32-wroom-32 and dht11 to read the humidty and temperature, besieds, it will send the meassage to the cloud platform. All communication is conducted through MQTT. 打分標準 您應該對以下代碼進行評級&#xff0c;并且必須遵守如…

swift 對象轉Json

在 Swift 中將對象轉換為 JSON 可以通過以下方法實現&#xff1a; 使用 Codable 協議 Swift 的 Codable 協議&#xff08;Encodable 和 Decodable 的組合&#xff09;是處理 JSON 編碼和解碼的推薦方式。 struct Person: Codable {var name: Stringvar age: Int }let person…

Python學習Day43

學習來源&#xff1a;浙大疏錦行 import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt from PIL import Image import os # 設置隨機…