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

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

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ù)量,默認5replicas副本分區(qū)數(shù)量,默認1createIndex索引不存在時,是否自動創(chuàng)建索引,默認true 不建議自動創(chuàng)建索引(自動創(chuàng)建的索引 是按著默認類型和默認分詞器)
注解:@Id 表示索引的主鍵
注解:@Field 用來描述字段的ES數(shù)據(jù)類型,是否分詞等配置,等于Mapping描述
index設(shè)置字段是否索引,默認是true,如果是false則該字段不能被查詢store標記原始字段值是否應(yīng)該存儲在 Elasticsearch 中,默認值為false,以便于快速檢索。雖然store占用磁盤空間,但是減少了計算。type數(shù)據(jù)類型(text、keyword、date、object、geo等)analyzer對字段使用分詞器,注意一般如果要使用分詞器,字段的type一般是text。format定義日期時間格式
注解:@CompletionField 定義關(guān)鍵詞索引 要完成補全搜索
analyzer對字段使用分詞器,注意一般如果要使用分詞器,字段的type一般是text。searchAnalyzer顯示指定搜索時分詞器,默認是和索引是同一個,保證分詞的一致性。maxInputLength設(shè)置單個輸入的長度,默認為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 為細粒度分詞
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)文章
Spring集成Druid連接池及監(jiān)控配置的全過程
java程序很大一部分要操作數(shù)據(jù)庫,為了提高性能操作數(shù)據(jù)庫的時候,有不得不使用數(shù)據(jù)庫連接池,下面這篇文章主要給大家介紹了關(guān)于Spring集成Druid連接池及監(jiān)控配置的相關(guān)資料,需要的朋友可以參考下2021-09-09
解析SpringBoot?搭建基于?MinIO?的高性能存儲服務(wù)的問題
Minio是Apache?License?v2.0下發(fā)布的對象存儲服務(wù)器,使用MinIO構(gòu)建用于機器學(xué)習(xí),分析和應(yīng)用程序數(shù)據(jù)工作負載的高性能基礎(chǔ)架構(gòu)。這篇文章主要介紹了SpringBoot?搭建基于?MinIO?的高性能存儲服務(wù),需要的朋友可以參考下2022-03-03
使用logback實現(xiàn)按自己的需求打印日志到自定義的文件里
這篇文章主要介紹了使用logback實現(xiàn)按自己的需求打印日志到自定義的文件里,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
解決spring中redistemplate不能用通配符keys查出相應(yīng)Key的問題
這篇文章主要介紹了解決spring中redistemplate不能用通配符keys查出相應(yīng)Key的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

