SpringBoot3集成ElasticSearch

来源:https://www.cnblogs.com/cicada-smile/archive/2023/08/16/17632955.html
-Advertisement-
Play Games

Elasticsearch是一個分散式、RESTful風格的搜索和數據分析引擎,適用於各種數據類型,數字、文本、地理位置、結構化數據、非結構化數據; ...


目錄

標簽:ElasticSearch8.Kibana8;

一、簡介

Elasticsearch是一個分散式、RESTful風格的搜索和數據分析引擎,適用於各種數據類型,數字、文本、地理位置、結構化數據、非結構化數據;

在實際的工作中,歷經過Elasticsearch從6.07.0的版本升級,而這次SpringBoot3和ES8.0的集成,雖然腳本的語法變化很小,但是Java客戶端的API語法變化很大;

二、環境搭建

1、下載安裝包

需要註意的是,這些安裝包的版本要選擇對應的,不然容易出問題;

軟體包:elasticsearch-8.8.2-darwin-x86_64.tar.gz
分詞器工具:elasticsearch-analysis-ik-8.8.2.zip
可視化工具:kibana-8.8.2-darwin-x86_64.tar.gz

2、服務啟動

不論是ES還是Kibana,在首次啟動後,會初始化很多配置文件,可以根據自己的需要做相關的配置調整,比如常見的埠調整,資源占用,安全校驗等;

1、啟動ES
elasticsearch-8.8.2/bin/elasticsearch

本地訪問:localhost:9200

2、啟動Kibana
kibana-8.8.2/bin/kibana

本地訪問:http://localhost:5601

# 3、查看安裝的插件
http://localhost:9200/_cat/plugins  ->  analysis-ik 8.8.2

三、工程搭建

1、工程結構

2、依賴管理

starter-elasticsearch組件中,實際上依賴的是elasticsearch-java組件的8.7.1版本;

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    <version>${spring-boot.version}</version>
</dependency>

3、配置文件

在上面環境搭建的過程中,已經禁用了用戶和密碼的登錄驗證,配置ES服務地址即可;

spring:
  # ElasticSearch配置
  elasticsearch:
    uris: localhost:9200

四、基礎用法

1、實體類

通過DocumentField註解描述ES索引結構的實體類,註意這裡JsonIgnoreProperties註解,解決索引中欄位和實體類非一一對應的而引起的JSON解析問題;

@JsonIgnoreProperties(ignoreUnknown = true)
@Document(indexName = "contents_index", createIndex = false)
public class ContentsIndex implements Serializable {

    private static final long serialVersionUID=1L;

    @Field(type= FieldType.Integer)
    private Integer id;

    @Field(type= FieldType.Keyword)
    private String title;

    @Field(type= FieldType.Keyword)
    private String intro;

    @Field(type= FieldType.Text)
    private String content;

    @Field(type= FieldType.Integer)
    private Integer createId;

    @Field(type= FieldType.Keyword)
    private String createName;

    @Field(type= FieldType.Date,format = DateFormat.date_hour_minute_second)
    private Date createTime;
}

2、初始化索引

基於ElasticsearchTemplate類和上述實體類,實現索引結構的初始化,並且將tb_contents表中的數據同步到索引中,最後通過ID查詢一條測試數據;

@Service
public class ContentsIndexService {
    private static final Logger log = LoggerFactory.getLogger(ContentsIndexService.class);

    @Resource
    private ContentsService contentsService ;
    @Resource
    private ElasticsearchTemplate template ;

    /**
     * 初始化索引結構和數據
     */
    public void initIndex (){
        // 處理索引結構
        IndexOperations indexOps = template.indexOps(ContentsIndex.class);
        if (indexOps.exists()){
            boolean delFlag = indexOps.delete();
            log.info("contents_index exists,delete:{}",delFlag);
            indexOps.createMapping(ContentsIndex.class);
        } else {
            log.info("contents_index not exists");
            indexOps.createMapping(ContentsIndex.class);
        }
        // 同步資料庫表記錄
        List<Contents> contentsList = contentsService.queryAll();
        if (contentsList.size() > 0){
            List<ContentsIndex> contentsIndexList = new ArrayList<>() ;
            contentsList.forEach(contents -> {
                ContentsIndex contentsIndex = new ContentsIndex() ;
                BeanUtils.copyProperties(contents,contentsIndex);
                contentsIndexList.add(contentsIndex);
            });
            template.save(contentsIndexList);
        }
        // ID查詢
        ContentsIndex contentsIndex = template.get("10",ContentsIndex.class);
        log.info("contents-index-10:{}",contentsIndex);
    }
}

3、倉儲介面

繼承ElasticsearchRepository介面,可以對ES這種特定類型的存儲庫進行通用增刪改查操作;在測試類中對該介面的方法進行測試;

// 1、介面定義
public interface ContentsIndexRepository extends ElasticsearchRepository<ContentsIndex,Long> {
}

// 2、介面測試
public class ContentsIndexRepositoryTest {
    @Autowired
    private ContentsIndexRepository contentsIndexRepository;

    @Test
    public void testAdd (){
        // 單個新增
        contentsIndexRepository.save(buildOne());
        // 批量新增
        contentsIndexRepository.saveAll(buildList()) ;
    }

    @Test
    public void testUpdate (){
        // 根據ID查詢後再更新
        Optional<ContentsIndex> contentsOpt = contentsIndexRepository.findById(14L);
        if (contentsOpt.isPresent()){
            ContentsIndex contentsId = contentsOpt.get();
            System.out.println("id=14:"+contentsId);
            contentsId.setContent("update-content");
            contentsId.setCreateTime(new Date());
            contentsIndexRepository.save(contentsId);
        }
    }

    @Test
    public void testQuery (){
        // 單個ID查詢
        Optional<ContentsIndex> contentsOpt = contentsIndexRepository.findById(1L);
        if (contentsOpt.isPresent()){
            ContentsIndex contentsId1 = contentsOpt.get();
            System.out.println("id=1:"+contentsId1);
        }
        // 批量ID查詢
        Iterator<ContentsIndex> contentsIterator = contentsIndexRepository
                                        .findAllById(Arrays.asList(10L,12L)).iterator();
        while (contentsIterator.hasNext()){
            ContentsIndex contentsIndex = contentsIterator.next();
            System.out.println("id="+contentsIndex.getId()+":"+contentsIndex);
        }
    }

    @Test
    public void testDelete (){
        contentsIndexRepository.deleteById(15L);
        contentsIndexRepository.deleteById(16L);
    }
}

4、查詢語法

無論是ElasticsearchTemplate類還是ElasticsearchRepository介面,都是對ES常用的簡單功能進行封裝,在實際使用時,複雜的查詢語法還是依賴ElasticsearchClient和原生的API封裝;

這裡主要演示七個查詢方法,主要涉及:ID查詢,欄位匹配,組合與範圍查詢,分頁與排序,分組統計,最大值查詢和模糊匹配;更多的查詢API還是要多看文檔中的案例才行;

public class ElasticsearchClientTest {

    @Autowired
    private ElasticsearchClient client ;

    @Test
    public void testSearch1 () throws IOException {
        // ID查詢
        GetResponse<ContentsIndex> resp = client.get(
                getReq ->getReq.index("contents_index").id("7"), ContentsIndex.class);
        if (resp.found()){
            ContentsIndex contentsIndex = resp.source() ;
            System.out.println("contentsIndex-7:"+contentsIndex);
        }
    }

    @Test
    public void testSearch2 () throws IOException {
        // 指定欄位匹配
        SearchResponse<ContentsIndex> resp = client.search(searchReq -> searchReq.index("contents_index")
                        .query(query -> query.match(field -> field
                        .field("createName").query("張三"))),ContentsIndex.class);
        printResp(resp);
    }

    @Test
    public void testSearch3 () throws IOException {
        // 組合查詢:姓名和時間範圍
        Query byName = MatchQuery.of(field -> field.field("createName").query("王五"))._toQuery();
        Query byTime = RangeQuery.of(field -> field.field("createTime")
                        .gte(JsonData.of("2023-07-10T00:00:00"))
                        .lte(JsonData.of("2023-07-12T00:00:00")))._toQuery();
        SearchResponse<ContentsIndex> resp = client.search(searchReq -> searchReq.index("contents_index")
                        .query(query -> query.bool(boolQuery -> boolQuery.must(byName).must(byTime))),ContentsIndex.class);
        printResp(resp);
    }

    @Test
    public void testSearch4 () throws IOException {
        // 排序和分頁,在14條數據中,根據ID倒序排列,從第5條往後取4條數據
        SearchResponse<ContentsIndex> resp = client.search(searchReq -> searchReq.index("contents_index")
                .from(5).size(4)
                .sort(sort -> sort.field(sortField -> sortField.field("id").order(SortOrder.Desc))),ContentsIndex.class);
        printResp(resp);
    }

    @Test
    public void testSearch5 () throws IOException {
        // 根據createId分組統計
        SearchResponse<ContentsIndex> resp = client.search(searchReq -> searchReq.index("contents_index")
                .aggregations("createIdGroup",agg -> agg.terms(term -> term.field("createId"))),ContentsIndex.class);
        Aggregate aggregate = resp.aggregations().get("createIdGroup");
        LongTermsAggregate termsAggregate = aggregate.lterms();
        Buckets<LongTermsBucket> buckets = termsAggregate.buckets();
        for (LongTermsBucket termsBucket : buckets.array()) {
            System.out.println(termsBucket.key() + " : " + termsBucket.docCount());
        }
    }

    @Test
    public void testSearch6 () throws IOException {
        // 查詢最大的ID
        SearchResponse<ContentsIndex> resp = client.search(searchReq -> searchReq.index("contents_index")
                .aggregations("maxId",agg -> agg.max(field -> field.field("id"))),ContentsIndex.class);
        for (Map.Entry<String, Aggregate> entry : resp.aggregations().entrySet()){
            System.out.println(entry.getKey()+":"+entry.getValue().max().value());
        }
    }

    @Test
    public void testSearch7 () throws IOException {
        // 模糊查詢title欄位,允許1個誤差
        Query byContent = FuzzyQuery.of(field -> field.field("title").value("設計").fuzziness("1"))._toQuery();
        SearchResponse<ContentsIndex> resp = client.search(
                searchReq -> searchReq.index("contents_index").query(byContent),ContentsIndex.class);
        printResp(resp);
    }

    private void printResp (SearchResponse<ContentsIndex> resp){
        TotalHits total = resp.hits().total();
        System.out.println("total:"+total);
        List<Hit<ContentsIndex>> hits = resp.hits().hits();
        for (Hit<ContentsIndex> hit: hits) {
            ContentsIndex contentsIndex = hit.source();
            System.out.println(hit.id()+":"+contentsIndex);
        }
    }
}

五、參考源碼

文檔倉庫:
https://gitee.com/cicadasmile/butte-java-note

源碼倉庫:
https://gitee.com/cicadasmile/butte-spring-parent
Gitee主頁: https://gitee.com/cicadasmile/butte-java-note
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ## String的三種初始化方式 ```java public class Test { public static void main(String[] args) { String str1 = "Hello, World !"; //直接初始化 String str2 = new Strin ...
  • package com.yc.cloud.excel.util; import cn.hutool.poi.excel.ExcelWriter; import lombok.extern.slf4j.Slf4j; import org.apache.poi.hssf.usermodel.HSSFCl ...
  • ## 1、說明 一般情況下,都是在model中指定一個資料庫連接參數即可。但某些情況下,相同的庫表會在不同地區都有部署,這個時候需要按地區進行切換(只有一個model情況下)。 ## 2、多model繼承方式 Model層代碼 ``` //A地區的資料庫 class A extends Model ...
  • [TOC] ## 1. 好險,差點被噴 早幾天發了一篇文章:[《僅三天,我用 GPT-4 生成了性能全網第一的 Golang Worker Pool,輕鬆打敗 GitHub 萬星項目》](https://www.danielhu.cn/golang-gopool-1/),這標題是挺容易被懟,哇咔咔; ...
  • 變數 變數是一種可以賦給值的標簽。每一個變數都指向一個相關聯的值,下列代碼中 message 即為變數,指向的值為“Hello Python world !” message = "Hello Python world!" print(message) 第二行的 print() 函數用於列印輸出這個 ...
  • C++ STL 中的非變易演算法(Non-modifying Algorithms)是指那些不會修改容器內容的演算法,是C++提供的一組模板函數,該系列函數不會修改原序列中的數據,而是對數據進行處理、查找、計算等操作,並通過迭代器實現了對序列元素的遍歷與訪問。由於迭代器與演算法是解耦的,因此非變易演算法可以... ...
  • # 將Markdown文件上傳到博客園 # 1.下載python 下載地址為:http://npm.taobao.org/mirrors/python/ 安裝為3.10.11版本 在cmd視窗輸入python,彈出以下視窗為安裝成功 ![image-20230816102551883](https: ...
  • 所謂**數據轉置**,就是是將原始數據表格沿著對角線翻折,使原來的行變成新的列,原來的列變成新的行,從而更方便地進行數據分析和處理。 `pandas`中`DataFrame`的轉置非常簡單,每個`DataFrame`對象都有一個`T`屬性,通過這個屬性就能得到轉置之後的`DataFrame`。下麵介 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...