第一步,開啟本地的 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 查看創建情況