国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringBoot3集成ElasticSearch

這篇具有很好參考價(jià)值的文章主要介紹了SpringBoot3集成ElasticSearch。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

目錄
  • 一、簡介
  • 二、環(huán)境搭建
    • 1、下載安裝包
    • 2、服務(wù)啟動(dòng)
  • 三、工程搭建
    • 1、工程結(jié)構(gòu)
    • 2、依賴管理
    • 3、配置文件
  • 四、基礎(chǔ)用法
    • 1、實(shí)體類
    • 2、初始化索引
    • 3、倉儲(chǔ)接口
    • 4、查詢語法
  • 五、參考源碼

標(biāo)簽:ElasticSearch8.Kibana8;

一、簡介

Elasticsearch是一個(gè)分布式、RESTful風(fēng)格的搜索和數(shù)據(jù)分析引擎,適用于各種數(shù)據(jù)類型,數(shù)字、文本、地理位置、結(jié)構(gòu)化數(shù)據(jù)、非結(jié)構(gòu)化數(shù)據(jù);

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

二、環(huán)境搭建

1、下載安裝包

需要注意的是,這些安裝包的版本要選擇對(duì)應(yīng)的,不然容易出問題;

軟件包: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、服務(wù)啟動(dòng)

不論是ES還是Kibana,在首次啟動(dòng)后,會(huì)初始化很多配置文件,可以根據(jù)自己的需要做相關(guān)的配置調(diào)整,比如常見的端口調(diào)整,資源占用,安全校驗(yàn)等;

SpringBoot3集成ElasticSearch

1、啟動(dòng)ES
elasticsearch-8.8.2/bin/elasticsearch

本地訪問:localhost:9200

2、啟動(dòng)Kibana
kibana-8.8.2/bin/kibana

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

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

三、工程搭建

1、工程結(jié)構(gòu)

SpringBoot3集成ElasticSearch

2、依賴管理

starter-elasticsearch組件中,實(shí)際上依賴的是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、配置文件

在上面環(huán)境搭建的過程中,已經(jīng)禁用了用戶和密碼的登錄驗(yàn)證,配置ES服務(wù)地址即可;

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

四、基礎(chǔ)用法

1、實(shí)體類

通過DocumentField注解描述ES索引結(jié)構(gòu)的實(shí)體類,注意這里JsonIgnoreProperties注解,解決索引中字段和實(shí)體類非一一對(duì)應(yīng)的而引起的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類和上述實(shí)體類,實(shí)現(xiàn)索引結(jié)構(gòu)的初始化,并且將tb_contents表中的數(shù)據(jù)同步到索引中,最后通過ID查詢一條測試數(shù)據(jù);

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

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

    /**
     * 初始化索引結(jié)構(gòu)和數(shù)據(jù)
     */
    public void initIndex (){
        // 處理索引結(jié)構(gòu)
        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);
        }
        // 同步數(shù)據(jù)庫表記錄
        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、倉儲(chǔ)接口

繼承ElasticsearchRepository接口,可以對(duì)ES這種特定類型的存儲(chǔ)庫進(jìn)行通用增刪改查操作;在測試類中對(duì)該接口的方法進(jìn)行測試;

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

// 2、接口測試
public class ContentsIndexRepositoryTest {
    @Autowired
    private ContentsIndexRepository contentsIndexRepository;

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

    @Test
    public void testUpdate (){
        // 根據(jù)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 (){
        // 單個(gè)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接口,都是對(duì)ES常用的簡單功能進(jìn)行封裝,在實(shí)際使用時(shí),復(fù)雜的查詢語法還是依賴ElasticsearchClient和原生的API封裝;

這里主要演示七個(gè)查詢方法,主要涉及:ID查詢,字段匹配,組合與范圍查詢,分頁與排序,分組統(tǒng)計(jì),最大值查詢和模糊匹配;更多的查詢API還是要多看文檔中的案例才行;文章來源地址http://www.zghlxwxcb.cn/news/detail-650358.html

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 {
        // 組合查詢:姓名和時(shí)間范圍
        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條數(shù)據(jù)中,根據(jù)ID倒序排列,從第5條往后取4條數(shù)據(jù)
        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 {
        // 根據(jù)createId分組統(tǒng)計(jì)
        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個(gè)誤差
        Query byContent = FuzzyQuery.of(field -> field.field("title").value("設(shè)計(jì)").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

到了這里,關(guān)于SpringBoot3集成ElasticSearch的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • SpringBoot3集成ElasticSearch

    SpringBoot3集成ElasticSearch

    目錄 一、簡介 二、環(huán)境搭建 1、下載安裝包 2、服務(wù)啟動(dòng) 三、工程搭建 1、工程結(jié)構(gòu) 2、依賴管理 3、配置文件 四、基礎(chǔ)用法 1、實(shí)體類 2、初始化索引 3、倉儲(chǔ)接口 4、查詢語法 五、參考源碼 標(biāo)簽:ElasticSearch8.Kibana8; Elasticsearch是一個(gè)分布式、RESTful風(fēng)格的搜索和數(shù)據(jù)分析引擎

    2024年02月12日
    瀏覽(19)
  • SpringBoot3集成Quartz

    SpringBoot3集成Quartz

    目錄 一、簡介 二、工程搭建 1、工程結(jié)構(gòu) 2、依賴管理 3、數(shù)據(jù)庫 4、配置文件 三、Quartz用法 1、初始化加載 2、新增任務(wù) 3、更新任務(wù) 4、暫停任務(wù) 5、恢復(fù)任務(wù) 6、執(zhí)行一次 7、刪除任務(wù) 8、任務(wù)執(zhí)行 四、參考源碼 標(biāo)簽:Quartz.Job.Scheduler; Quartz由Java編寫的功能豐富的開源作業(yè)

    2024年02月13日
    瀏覽(16)
  • SpringBoot3數(shù)據(jù)庫集成

    SpringBoot3數(shù)據(jù)庫集成

    標(biāo)簽:Jdbc.Druid.Mybatis.Plus; 項(xiàng)目工程中,集成數(shù)據(jù)庫實(shí)現(xiàn)對(duì)數(shù)據(jù)的增曬改查管理,是最基礎(chǔ)的能力,而對(duì)于這個(gè)功能的實(shí)現(xiàn),其組件選型也非常豐富; 通過如下幾個(gè)組件來實(shí)現(xiàn)數(shù)據(jù)庫的整合; Druid連接池 :阿里開源的數(shù)據(jù)庫連接池,并且提供 SQL 執(zhí)行的監(jiān)控能力; MybatisPlu

    2024年02月13日
    瀏覽(28)
  • Elasticsearch 搜索測試與集成Springboot3

    Elasticsearch 搜索測試與集成Springboot3

    Elasticsearch是專門做 搜索 的,它非常擅長以下方面的問題 Elasticsearch對(duì)模糊搜索非常擅長(搜索速度很快) 從Elasticsearch搜索到的數(shù)據(jù)可以根據(jù) 評(píng)分 過濾掉大部分的,只要返回評(píng)分高的給用戶就好了(原生就支持排序) 沒有那么準(zhǔn)確的也能搜出相關(guān)的結(jié)果(能匹配有相

    2024年01月22日
    瀏覽(30)
  • Java21 + SpringBoot3集成WebSocket

    Java21 + SpringBoot3集成WebSocket

    近日心血來潮想做一個(gè)開源項(xiàng)目,目標(biāo)是做一款可以適配多端、功能完備的模板工程,包含后臺(tái)管理系統(tǒng)和前臺(tái)系統(tǒng),開發(fā)者基于此項(xiàng)目進(jìn)行裁剪和擴(kuò)展來完成自己的功能開發(fā)。 本項(xiàng)目為前后端分離開發(fā),后端基于 Java21 和 SpringBoot3 開發(fā),前端提供了vue、angular、react、uniap

    2024年01月23日
    瀏覽(62)
  • 【springboot3.x 記錄】解決 springboot3 集成 mybatis-plus 報(bào) sqlSession 異常

    2022-12-30,作者最新發(fā)布了?3.5.3.1 版本,不需要使用快照版本了 ========================= springboot3 已經(jīng)發(fā)布正式版,第一時(shí)間嘗鮮看看如何,但是在集成?mybatis-plus 最新版 3.5.2 的時(shí)候發(fā)現(xiàn)提示異常。 看來 springboot3 在注入這塊做了調(diào)整,但目前?mybatis-plus 并沒有適配到。 于是翻查

    2024年02月13日
    瀏覽(17)
  • springboot3 集成mybatis 和通用mapper

    springboot3 集成mybatis 和通用mapper

    xml版本查看:https://www.cnblogs.com/binz/p/6564490.html springboot3.x以前的版本查看 https://www.cnblogs.com/binz/p/17421063.html springboot3.x查看??https://www.cnblogs.com/binz/p/17654403.html 1、pom引用 !-- openapi、 swagger3、knife4j配置,適用boot3 -- !-- https://doc.xiaominfo.com -- dependency groupId com.github.xiaoymin/ groupI

    2024年02月11日
    瀏覽(25)
  • SpringBoot3集成Kafka優(yōu)雅實(shí)現(xiàn)信息消費(fèi)發(fā)送

    ???????首先,你的JDK是否已經(jīng)是8+了呢? ???????其次,你是否已經(jīng)用上SpringBoot3了呢? ???????最后,這次分享的是SpringBoot3下的kafka發(fā)信息與消費(fèi)信息。 ???????這次的場景是springboot3+多數(shù)據(jù)源的數(shù)據(jù)交換中心(數(shù)倉)需要消費(fèi)Kafka里的上游推送信息,這里做數(shù)據(jù)

    2024年02月02日
    瀏覽(29)
  • SpringBoot3.1.7集成Kafka和Kafka安裝

    SpringBoot3.1.7集成Kafka和Kafka安裝

    我們?cè)诤芏嘞到y(tǒng)開發(fā)都需要用到消息中間件,目前來說Kafka憑借其優(yōu)秀的性能,使得它的使用率已經(jīng)是名列前茅了,所以今天我們將它應(yīng)用到我們的系統(tǒng) 在使用一個(gè)中間件一定要考慮版本的兼容性,否則后面會(huì)遇到很多問題,首先我們打開Spring的官網(wǎng):Spring for Apache Kafka Spr

    2024年01月23日
    瀏覽(29)
  • 【SpringBoot3】Spring Boot 3.0 集成 Redis 緩存

    Redis緩存是一個(gè)開源的使用ANSIC語言編寫、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫,并提供多種語言的API。它主要用于作為數(shù)據(jù)庫、緩存和消息中間件,以快速讀寫和豐富的數(shù)據(jù)結(jié)構(gòu)支持而著稱。 在應(yīng)用程序和數(shù)據(jù)庫之間,Redis緩存作為一個(gè)中間層起著關(guān)鍵

    2024年02月21日
    瀏覽(90)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包