SpringBoot集成ElasticSearch的四種方式(主要講解ES官方推薦方式)
- TransportClient:這種方式即將棄用 官方將在8.0版本徹底去除
- Data-Es:Spring提供的封裝的方式,由于是Spring提供的,所以每個SpringBoot版本對應的ElasticSearch,具體這么個對應的版本,自己去官網(wǎng)看
- ElasticSearch SQL:將Elasticsearch的
Query DSL
用SQL
轉(zhuǎn)換查詢,早期有一個第三方的插件Elasticsearch-SQL,后來隨著官方也開始做這方面,這個插件好像就沒怎么更新了,有興趣的可以查看https://www.cnblogs.com/jajian/p/10053504.html - Rest Client:官方推薦使用,所以我們采用這個方式,這個分為兩個Low Level REST Client和High Level REST Client,Low Level REST Client是早期出的API比較簡陋了,還需要自己去拼寫
Query DSL
,High Level REST Client使用起來更好用,更符合面向?qū)ο蟮母杏X,我們下面使用High Rest Client
注意:我使用的是ES7.6.1版本,等會pom文件依賴時,版本必須與之對應
1.創(chuàng)建Maven項目
2.導入pom依賴
<dependencies>
<!--SpringBoot集成Es的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!--springbootweb包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--test測試包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--json序列化包-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.15</version>
</dependency>
</dependencies>
pom導包完成后、需要點開Maven查看引入的elasticsearch-rest-high-level-client的版本是否與你的ElasticSearch版本一致
如果不一致需要自己去控制版本(如下代碼)
<properties>
<java.version>1.8</java.version>
<!--這里是你的es的版本-->
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
3.SpringBoot項目的啟動類編寫(忽略)
4.編寫配置類(RestHighLevelClient)
// 表示這是一個配置類
@Configuration
public class RestElasticSearchClientConfig {
// 將方法的返回結(jié)果交給spring管理
@Bean
public RestHighLevelClient restHighLevelClient(){
// 主機ip和端口號以及協(xié)議
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return restHighLevelClient;
}
}
到這里我們RestHighLevelClient的配置就做完了
5.測試(使用RestHighLevelClient的Api)
編寫測試類,在類中自動注入RestHighLevelClient對象文章來源:http://www.zghlxwxcb.cn/news/detail-400313.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-400313.html
6.RestHighLevelClient的Api使用(關(guān)于索引)
6.1 簡單索引的創(chuàng)建
// 測試索引的創(chuàng)建(不帶mapping,ElasticSearch默認會根據(jù)你的添加的文檔來創(chuàng)建mapping)
@Test
void testCreateIndex() throws IOException {
// 創(chuàng)建索引的請求
CreateIndexRequest nan_index = new CreateIndexRequest("nan_index");
// client執(zhí)行請求
CreateIndexResponse response = restHighLevelClient.indices().create(nan_index, RequestOptions.DEFAULT);
System.out.println(response);
}
6.2自定義mapping創(chuàng)建索引
// 帶上自定義的mapping來創(chuàng)建索引
@Test
void testCreateMappingIndex() throws IOException {
// 創(chuàng)建索引的請求
CreateIndexRequest indexRequest = new CreateIndexRequest
到了這里,關(guān)于Java使用Springboot集成Es官方推薦(RestHighLevelClient)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!