springboot如何整合elasticsearch
前言
推薦首先查看spring boot對應(yīng)elasticsearch版本,選擇合適的版本整合,推薦以spring boot版本為主,因為項目中集成的框不止是es,根據(jù)spring boot去安裝對應(yīng)版本的es。
Spring Data Elasticsearch - 參考文檔,這是官方文檔,建議一定參照文檔,這個文檔真的很詳細(xì)。

另外,springboot操作elasticsearch有兩種常用方式:
不管使用哪一種,文章開頭的參考文檔地址里邊都有詳細(xì)介紹,可以下載一個瀏覽器翻譯插件,這樣看起來更輕松。

Spring Data Elasticsearch
這是Spring官方最推薦的,就像JPA,Mybatisplus一樣,在DAO層繼承ElasticsearchRepository接口,就可以使用封裝好的一些常見的操作了,用起來簡單方便。

ElasticsearchRestTemplate
封裝的就是High Level REST Client,這是基于HTTP協(xié)議的客戶端,是ES官方推薦使用的,也是可以使用的,但是要求對ES的DSL語句熟悉,方便自己做復(fù)雜的增刪改查。

不同方式演示
首先需要搞清楚映射關(guān)系,參考官方文檔這部分,內(nèi)容過多,就不一一寫了。

簡單看一下
注解:@Document用來聲明Java對象與ElasticSearch索引的關(guān)系
indexName索引名稱(是字母的話必須是小寫字母)type索引類型shards主分區(qū)數(shù)量,默認(rèn)5replicas副本分區(qū)數(shù)量,默認(rèn)1createIndex索引不存在時,是否自動創(chuàng)建索引,默認(rèn)true 不建議自動創(chuàng)建索引(自動創(chuàng)建的索引 是按著默認(rèn)類型和默認(rèn)分詞器)
注解:@Id 表示索引的主鍵
注解:@Field 用來描述字段的ES數(shù)據(jù)類型,是否分詞等配置,等于Mapping描述
index設(shè)置字段是否索引,默認(rèn)是true,如果是false則該字段不能被查詢store標(biāo)記原始字段值是否應(yīng)該存儲在 Elasticsearch 中,默認(rèn)值為false,以便于快速檢索。雖然store占用磁盤空間,但是減少了計算。type數(shù)據(jù)類型(text、keyword、date、object、geo等)analyzer對字段使用分詞器,注意一般如果要使用分詞器,字段的type一般是text。format定義日期時間格式
注解:@CompletionField 定義關(guān)鍵詞索引 要完成補全搜索
analyzer對字段使用分詞器,注意一般如果要使用分詞器,字段的type一般是text。searchAnalyzer顯示指定搜索時分詞器,默認(rèn)是和索引是同一個,保證分詞的一致性。maxInputLength設(shè)置單個輸入的長度,默認(rèn)為50 UTF-16 代碼點
集成先決配置
依賴包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
yml簡單配置
server:
port: 8082
spring:
elasticsearch:
rest:
uris: 192.168.25.131:9200
實體類
@Data
@AllArgsConstructor
@NoArgsConstructor
//indexName名字如果是字母那么必須是小寫字母
@Document(indexName = "student")
public class Student {
@Id
@Field(store = true, type = FieldType.Keyword)
private String sId;
@Field(store = true, type = FieldType.Keyword)
private String sName;
@Field(store = true, type = FieldType.Text, analyzer = "ik_smart")
//Text可以分詞 ik_smart=粗粒度分詞 ik_max_word 為細(xì)粒度分詞
private String sAddress;
@Field(index = false, store = true, type = FieldType.Integer)
private Integer sAge;
@Field(index = false, store = true, type = FieldType.Date, format = DateFormat.basic_date_time)
private Date sCreateTime;
@Field(type = FieldType.Keyword)
private String[] sCourseList; //數(shù)組類型 由數(shù)組中第一個非空值決定(這里數(shù)組和集合一個意思了)
@Field(type = FieldType.Keyword)
private List<String> sColorList; //集合類型 由數(shù)組中第一個非空值決定
}
Spring Data Elasticsearch方式
先看文檔了解一下定義接口方法的規(guī)則吧,前邊說過,這種方式就是類似JPA和Mybatisplus的方式,所以不難理解哈。
定義mapper
/**
* @author: zhouwenjie
* @description:
* @create: 2022-05-12 17:37
* ElasticsearchRepository<T, ID> T:實體類泛型,ID:實體類主鍵類型
**/
public interface StudentMapper extends ElasticsearchRepository<Student, String> {
}
使用es自帶的一些增刪改查方法
如下圖,可以看到ElasticsearchRepository本身自帶了一些簡單curd方法。

測試
@Resource
StudentMapper studentMapper;
@Test
void contextLoads3() {
Optional<Student> optionalStudent = studentMapper.findById("2");
System.out.println(optionalStudent.get());
}
使用自定義的方法
規(guī)則參考官網(wǎng)的這部分

自定義方法
/**
* @author: zhouwenjie
* @description:
* @create: 2022-05-12 17:37
* ElasticsearchRepository<T, ID> T:實體類泛型,ID:實體類主鍵類型
**/
public interface StudentMapper extends ElasticsearchRepository<Student, String> {
//提示方法名SName,但是s是小寫sName才可以
List<Student> findStudentBysName(String name);
}
測試
@Test
void contextLoads3() {
List<Student> students = studentMapper.findStudentBysName("fff");
System.out.println(students);
}
好了,測試到此為止,更多需求可以參照官方文檔自行實現(xiàn)。
ElasticsearchRestTemplate方式
返回結(jié)果,參照官方說明:

添加
@Test
void contextLoads2() {
List<String> colorList = new ArrayList<>();//顏色
colorList.add("red");
colorList.add("white");
colorList.add("black");
Student student = new Student("1", "mhh", "濟南", 12, new Date(), new String[]{"語文", "數(shù)學(xué)", "英語"}, colorList);
Student save = restTemplate.save(student);
System.out.println(save);
}

查詢
@Test
void contextLoads() {
Criteria criteria = new Criteria("sName").is("mhh").and("sAddress").is("濟南");
Query query = new CriteriaQuery(criteria);
SearchHits<Student> mapSearchHits = restTemplate.search(query, Student.class, IndexCoordinates.of("student"));
List<SearchHit<Student>> searchHits = mapSearchHits.getSearchHits();
for (SearchHit<Student> searchHit : searchHits) {
Student student = searchHit.getContent();
System.out.println(student);
}
}
更新
@Test
void contextLoads2() {
HashMap<String, Object> map = new HashMap<>();
map.put("sName","fff");
UpdateQuery.Builder builder = UpdateQuery.builder("1").withDocument(Document.from(map));
UpdateResponse update = restTemplate.update(builder.build(), IndexCoordinates.of("student"));
System.out.println(update);
}

刪除
@Test
void contextLoads2() {
String delete = restTemplate.delete("1",IndexCoordinates.of("student"));
System.out.println(delete);
}
這些演示都是最簡單的,根據(jù)實際情況推薦大家去官網(wǎng)查詢更多復(fù)雜用法。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Android設(shè)備如何保證數(shù)據(jù)同步寫入磁盤的實現(xiàn)
這篇文章主要介紹了Android設(shè)備如何保證數(shù)據(jù)同步寫入磁盤的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
Springboot如何讀取resources下的json配置文件
這篇文章主要介紹了Springboot如何讀取resources下的json配置文件問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
Spring?Boot?+?Spring?Batch?實現(xiàn)批處理任務(wù)的詳細(xì)教程
這篇文章主要介紹了Spring?Boot+Spring?Batch實現(xiàn)批處理任務(wù),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
java實現(xiàn)微信小程序加密數(shù)據(jù)解密算法
這篇文章主要為大家詳細(xì)介紹了java實現(xiàn)微信小程序加密數(shù)據(jù)解密算法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09
Springboot?通過FastJson實現(xiàn)bean對象和Json字符串互轉(zhuǎn)問題
這篇文章主要介紹了Springboot?通過FastJson實現(xiàn)bean對象和Json字符串互轉(zhuǎn),本文嘗試驗證兩種場景給大家詳細(xì)介紹,對Springboot?FastJson實現(xiàn)bean和Json互轉(zhuǎn)問題,感興趣的朋友一起看看吧2022-08-08
SpringBoot項目Maven下載依賴速度慢問題的解決方法
在使用Maven構(gòu)建項目時,有時會遇到下載依賴包速度慢的問題,為了提高下載速度,我們可以將默認(rèn)的倉庫地址替換為國內(nèi)鏡像源,所以本文介紹了SpringBoot項目Maven下載依賴速度慢問題的解決方法,需要的朋友可以參考下2024-08-08

