主頁 > 後端開發 > SpringBoot進階教程(七十三)整合elasticsearch

SpringBoot進階教程(七十三)整合elasticsearch

2022-03-07 06:14:56 後端開發

Elasticsearch 是一個分布式、高擴展、高實時的搜索與資料分析引擎,它能很方便的使大量資料具有搜索、分析和探索的能力,充分利用Elasticsearch的水平伸縮性,能使資料在生產環境變得更有價值,Elasticsearch 的實作原理主要分為以下幾個步驟,首先用戶將資料提交到Elasticsearch 資料庫中,再通過分詞控制器去將對應的陳述句分詞,將其權重和分詞結果一并存入資料,當用戶搜索資料時候,再根據權重將結果排名,打分,再將回傳結果呈現給用戶,

在上一篇文章linux安裝elasticsearch中,已經介紹了在linux安裝elasticsearch,這篇文章主要介紹介紹es的一些基礎的入門教程、docker安裝elasticsearch以及在springboot中整合elasticsearch,

v基礎概念

1.0 Node與Cluster

Node:單個Elastic實體稱為一個節點(node)

Cluster:一組節點構成一個集群(cluster)

當然,這也正是集群和節點最通俗的解釋,這個解釋適用于絕大部分,類似elasticsearch這種分布式架構,如之前講過的《詳解Redis Cluster集群》,你可以可以說node就是單個redis實體,這樣的實體我們稱為一個節點,多個這樣的節點組成的集群,正因為如此,我們在設計架構的時候,需要考慮不同環境的不同節點的節點名注意不要重復,避免配置集群遇到尷尬,

1.1 Index

由一個和多個分片組成,通過索引的名字在集群內進行唯一標識,索引是具有某種相似特征的檔案的集合,Elastic資料管理的頂層設計就叫做 Index(索引),類似mysql中的database,

索引也分為名次索引和動詞索引,

  • 索引(名詞):如前所述,一個 索引 類似于傳統關系資料庫中的一個 資料庫 ,是一個存盤關系型檔案的地方, 索引 (index) 的復數詞為 indices 或 indexes ,
  • 索引(動詞):索引一個檔案 就是存盤一個檔案到一個 索引 (名詞)中以便被檢索和查詢,這非常類似于 SQL 陳述句中的 INSERT 關鍵詞,除了檔案已存在時,新檔案會替換舊檔案情況之外,

這個也好理解,類似詞組"表演",看她的表演,表演的很精彩,這是兩個意思,

1.2 Document

Elasticsearch是面向檔案的,意味著它存盤整個物件或檔案,檔案是可以被索引的基本資訊單元,檔案用JSON表示,

例如:存盤員工資訊,那就是一個員工資訊代表一個檔案,多個檔案組成一個index,類似于關系型資料庫中的一條資料通過id在Type內進行唯一標識,

1.3 Type

類別,指索引內部的邏輯磁區,通過type的名字在索引內進行唯一標識,在查詢時如果沒有該值,則表示在整個索引中查詢,

例如:在員工表里,可以按照員工籍貫分組(北上、上海、廣州),也可以按照員工工種分組(職能、產品、運營),這種分組可以理解為type,

在7.x版會移除Type,Elasticsearch為何要在7.X版本中去除type

1.4 與關系型資料庫對比

Relational DBElasticsearch
資料庫(database) 索引 index
表(tables) 型別 types
行(rows) 檔案 documents
欄位(columns) ?elds

1.5 Mapping

定義檔案及其包含的欄位是如何存盤和索引的程序,類似于資料庫中的表結構定義,主要作用如下:

  • 定義index下的欄位名
  • 定義欄位型別,比如數值型、浮點型、布爾型等
  • 定義倒排索引相關的設定,比如是否索引、記錄position等

vdocker安裝Elasticsearch

在上一篇文章中,已經詳細介紹了linux安裝elasticsearch,這篇文章講解的elasticsearch主要圍繞docker展開,

2.0 拉取鏡像

docker pull docker.io/elasticsearch:版本號

版本號是可選的,默認使用latest

2.1 創建&運行容器

docker run -d --name=es7 \
-p 9200:9200 -p 9300:9300 \
-e "discovery.type=single-node" elasticsearch:7.5.1

注意:若創建es持久化目錄,則按下面的命令執行,

mkdir -p /data/elasticsearch
docker cp es7:/usr/share/elasticsearch/data /data/elasticsearch/
docker cp es7:/usr/share/elasticsearch/logs /data/elasticsearch/
docker rm -f es7
docker run -d --name=es7 \
  --restart=always \
  -p 9200:9200 -p 9300:9300 \
  -e "discovery.type=single-node" \
  -v /data/elasticsearch/data:/usr/share/elasticsearch/data \
  -v /data/elasticsearch/logs:/usr/share/elasticsearch/logs \
elasticsearch:7.5.1

注意:若es起不來,可能是容器沒有宿主機掛載的目錄的讀寫權限,那就需要賦予它讀寫權限: chmod 777 /data/elasticsearch

2.2 驗證效果

輸入ip + 埠號(9200)驗證,

2.3 安裝elasticsearch-head

docker pull mobz/elasticsearch-head:5

2.4 創建&運行head容器

docker run -d --name elasticsearch-head -p 9100:9100 mobz/elasticsearch-head:5

2.5 跨域問題

url訪問http://toutou.com:9100之后發現無法連接http://toutou.com:9200,需要在es服務端做CORS的配置,

修改docker中es7的elasticsearch.yml檔案

[root@localhost data]# docker exec -it es7 /bin/bash
[root@f1358d18c9be elasticsearch]# vi config/elasticsearch.yml

在elasticsearch.yml底部追加如下配置:

http.cors.enabled: true 
http.cors.allow-origin: "*"

保存以后退出docker并重啟docker實體,

[root@f1358d18c9be elasticsearch]# exit
exit
[root@localhost data]# docker restart es7
es7

2.6 驗證elasticsearch-head

SpringBoot進階教程(七十三)整合elasticsearch

2.7 安裝中文分詞器ik

注意:ik分詞器的版本需要和es的版本一致,

docker exec -it es7 /bin/bash
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.5.1/elasticsearch-analysis-ik-7.5.1.zip
-> Downloading https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.5.1/elasticsearch-analysis-ik-7.5.1.zip

進入plugins可以看到IK分詞器已經安裝成功,重啟docker實體即可,

SpringBoot進階教程(七十三)整合elasticsearch

vRESTful API

任何語言都可以使用RESTful API通過9200埠(默認埠號)和Elasticsearch進行通信,也可以用web客戶端(瀏覽器Sense插件、postman)訪問 Elasticsearch ,甚至直接使用curl命令就可以和Elasticsearch互動,

Elasticsearch為很多語言(Groovy、JavaScript、.NET、 PHP、 Perl、 Python 和 Ruby)提供了官方客戶端,詳情:Elasticsearch Clients,

3.0 Elasticsearch請求格式:

Elasticsearch請求和我們認識的其它HTTP請求一樣,由多個部件組成,具體格式如下:

curl -X<VERB> '<PROTOCOL>://<HOST>:<PORT>/<PATH>?<QUERY_STRING>' -d '<BODY>'

< > 標記的部件釋義:

  • VERB:HTTP請求方法: GET、POST、PUT、DELETE、HEAD...  SpringBoot進階教程(七十三)整合elasticsearch
    GET:標識該操作是用于獲取服務端的資源,可以理解為select操作
    POST:用于向服務端新增資料,常用于提交表單,可以理解為insert操作
    PUT:用于向服務端更新資料,與post的使用很相似,可以理解為update操作
    DELETE:標識該操作是:用于洗掉服務端的資源,可以理解為delete操作
    HEAD:只請求頁面首部,回應報文中沒有物體的主體部分(沒有body體)
    點擊查看幾種http方法的區別...
  • PROTOCOL:http 或者 https SpringBoot進階教程(七十三)整合elasticsearch
    概念:
    HTTP:是互聯網上應用最為廣泛的一種網路協議,是一個客戶端和服務器端請求和應答的標準(TCP),用于從WWW服務器傳輸超文本到本地瀏覽器的傳輸協議,它可以使瀏覽器更加高效,使網路傳輸減少,
    HTTPS:是以安全為目標的HTTP通道,簡單講是HTTP的安全版,即HTTP下加入SSL層,HTTPS的安全基礎是SSL,因此加密的詳細內容就需要SSL,
    區別:
    1.https協議需要到ca申請證書,一般免費證書很少,需要交費,
    2.http是超文本傳輸協議,資訊是明文傳輸,https 則是具有安全性的ssl加密傳輸協議,
    3.http和https使用的是完全不同的連接方式,用的埠也不一樣,前者是80,后者是443,
    4.http的連接很簡單,是無狀態的;HTTPS協議是由SSL+HTTP協議構建的可進行加密傳輸、身份認證的網路協議,比http協議安全,
    點擊查看http和https的區別
  • HOST:Elasticsearch 集群中任意節點的主機名,或者用 localhost 代表本地機器上的節點,
  • PORT:服務的埠號,默認是9200,
  • PATH:API 的終端路徑(例如 _count 將回傳集群中檔案數量),Path可能包含多個組件,例如: _cluster/stats _nodes/stats/jvm
  • QUERY_STRING:任意可選的查詢字串引數 (例如 ?pretty 將格式化地輸出JSON回傳值,使其更容易閱讀)
  • BODY:一個 JSON格式的請求體(如果請求需要的話)

3.1 計算集群中檔案的數量

命令列格式: curl -XGET http://test.com:9200/_count?pretty

SpringBoot進階教程(七十三)整合elasticsearch

當然,也可以考慮使用其他工具,例如postman,

SpringBoot進階教程(七十三)整合elasticsearch

3.2 集群健康

Elasticsearch的集群監控資訊中包含了許多的統計資料,其中最為重要的一項就是集群健康 , 它在 status 欄位中展示為green、yellow或者red,

curl http://test.com:9200/_cluster/health

postman請求回傳結果如下:

SpringBoot進階教程(七十三)整合elasticsearch

{
    "cluster_name": "my-application",
    "status": "green",
    "timed_out": false,
    "number_of_nodes": 1,//集群節點數
    "number_of_data_nodes": 1,//資料節點數量
    "active_primary_shards": 0,//主分片數量
    "active_shards": 0,//可用的分片數量
    "relocating_shards": 0,//正在重新分配的分片數量,在新加或者減少節點的時候會發生
    "initializing_shards": 0,//正在初始化的分片數量,新建索引或者剛啟動會存在,時間很短
    "unassigned_shards": 0,//沒有分配的分片,一般就是那些名存實不存的副本分片
    "delayed_unassigned_shards": 0,
    "number_of_pending_tasks": 0,
    "number_of_in_flight_fetch": 0,
    "task_max_waiting_in_queue_millis": 0,
    "active_shards_percent_as_number": 100
}

3.3 status三種狀態值:

  • green:所有的主分片和副本分片都正常運行,
  • yellow:所有的主分片都正常運行,但不是所有的副本分片都正常運行,
  • red:有主分片沒能正常運行,

更多引數介紹:

索引級別集群狀態,可以細致查看到底是哪個索引引起集群的故障的

curl http://test.com:9200/_cluster/health?level=indices

分片級別集群狀態,可以細致查看到底是哪個分片引起的集群故障

curl http://test.com:9200/_cluster/health?level=shards

阻塞查看集群狀態,適用于自動化腳本,當狀態變為指定狀態或者更好就回傳繼續執行,

curl http://test.com:9200/_cluster/health?wait_for_status=yellow

v操作Elasticsearch

4.1 索引操作

4.1.1 查看索引是否存在

curl -i -XHEAD 'http://toutou.com:9200/city'

若索引存在:


HTTP/1.1 200 OK
content-type: application/json; charset=UTF-8
content-length: 239

若索引不存在:


HTTP/1.1 404 Not Found
content-type: application/json; charset=UTF-8
content-length: 395

4.1.2 創建Index

創建一個非結構化的索引,需要使用PUT請求,例如創建一個名為city的索引,

curl -X PUT '127.0.0.1:9200/city'

回傳結果:

{
    "acknowledged":true,"
    shards_acknowledged":true,
    "index":"city"
}

acknowledged=true表示操作成功,

創建一個結構化的索引:

SpringBoot進階教程(七十三)整合elasticsearch

{
    "settings":{
        "number_of_shards":3,
        "number_of_replicas":1
    },
    "mappings":{
        "properties":{
            "name":{
                "type":"text",
                "analyzer":"ik_max_word",
                "search_analyzer":"ik_max_word"
            },
            "level":{
                "type":"integer"
            },
            "address":{
                "type":"text",
                "analyzer":"ik_smart",
                "search_analyzer":"ik_smart"
            },
            "createTime":{
                "type":"date",
                "format":"yyyy-MM-dd HH:mm:ss || yyyy-MM-dd || epoch_millis"
            }
        }
    }
}
View Code

number_of_shards表示分片個數,number_of_replicas表示備份個數,

注意:在上文中已經介紹了,在在7.x版會移除Type,所以這里不需要再指定type, 相反若指定type了的話會報錯, Root mapping definition has unsupported parameters

建議使用elasticsearch最新版本,若安裝的是低于elasticsearch7版本的elasticsearch,可以使用下面的方式創建索引,

{
    "settings":{
        "number_of_shards":3,
        "number_of_replicas":1
    },
    "mappings":{
        "hotel":{
            "properties":{
                "level":{
                    "type":"integer"
                },
                "address":{
                    "type":"text",
                    "analyzer":"ik_max_word"
                },
                "createTime":{
                    "type":"date",
                    "format":"yyyy-MM-dd HH:mm:ss || yyyy-MM-dd || epoch_millis"
                }
            }
        },
        "restaurant":{
            "properties":{
                "type":{
                    "type":"text",
                    "analyzer":"ik_smart"
                },
                "price":{
                    "type":"integer"
                }
            }
        }
    }
}
View Code

4.1.3 洗掉Index

$ curl -X DELETE '127.0.0.1:9200/city'

回傳結果:

{"acknowledged":true}

4.2 插入資料

4.2.1 插入指定id的資料

在 es 中,插入資料分為指定檔案id插入和自動產生檔案id插入

指定檔案id插入,其中我們指定資料ID為1,

SpringBoot進階教程(七十三)整合elasticsearch

生成id=1的資料,

注意,在在7.x版會移除Type,所以插入資料的url需要加上 _doc ,即: http://toutou.com:9200/city/_doc/1 ,具體規則可以看看這里

自動產生檔案id插入,

SpringBoot進階教程(七十三)整合elasticsearch

4.3 修改資料

SpringBoot進階教程(七十三)整合elasticsearch

 

 

4.4 查詢資料

4.4.1 ID查詢GET

SpringBoot進階教程(七十三)整合elasticsearch

4.4.2 條件查詢POST

查詢5星級酒店,

SpringBoot進階教程(七十三)整合elasticsearch

4.5 洗掉資料

curl -X DELETE 'toutou.com:9200/city/_doc/2'

vSpringBoot整合Elasticsearch

spring-boot-starter-data-elasticsearch除錯了很久,嘗試的很多方法,始終報錯: NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{wlOJEdIeQqKrmiBiUuJVzQ}{toutou.com}{192.168.118.137:9300}]] ,看了一些相關介紹和博客,Spring Data Elasticsearch和Elasticsearch還有Spring Boot的版本需要全部一一對應上,才能使用,感覺太麻煩,新專案還好說,線上專案誰有功夫去跟你協調這些版本統一啊,費老勁了,果斷棄用了,如果有大佬這塊有好上手的兼容辦法,還請多多指點,

5.1 添加pom參考

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <!--<version>7.5.1</version>-->
        </dependency>

注意:如果是springboot程式的話, org.elasticsearch.client 參考的版本號 7.5.1 最好注釋掉,不然會報下面這個錯:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'indexController': Unsatisfied dependency expressed through field 'cityEsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cityEsServiceImpl': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource [learn/service/impl/EsConfig.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.elasticsearch.client.RestHighLevelClient] from ClassLoader [sun.misc.Launcher$AppClassLoader@18b4aac2]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202)
    at learn.web.Application.main(Application.java:18)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cityEsServiceImpl': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource [learn/service/impl/EsConfig.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.elasticsearch.client.RestHighLevelClient] from ClassLoader [sun.misc.Launcher$AppClassLoader@18b4aac2]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 19 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource [learn/service/impl/EsConfig.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.elasticsearch.client.RestHighLevelClient] from ClassLoader [sun.misc.Launcher$AppClassLoader@18b4aac2]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:570)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 32 common frames omitted
Caused by: java.lang.IllegalStateException: Failed to introspect Class [org.elasticsearch.client.RestHighLevelClient] from ClassLoader [sun.misc.Launcher$AppClassLoader@18b4aac2]
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:507)
    at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:367)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.buildLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:207)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.findLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:189)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(InitDestroyAnnotationBeanPostProcessor.java:128)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(CommonAnnotationBeanPostProcessor.java:297)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:1077)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:567)
    ... 41 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/elasticsearch/client/Cancellable
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.getDeclaredMethods(Class.java:1975)
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:489)
    ... 48 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.elasticsearch.client.Cancellable
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 52 common frames omitted
View Code

因為就像上文提到的data與es version沖突似的, org.elasticsearch.client 也有版本之間的兼容性問題,把 org.elasticsearch.client 的版本號去掉由SpringBoot來管理依賴的版本即可,

5.2 添加EsConfig

import com.google.gson.Gson;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author toutou
 * @date by 2021/02
 * @des
 */
@Configuration
public class EsConfig {

    public Gson gson(){
        return new Gson();
    }

    @Bean
    public RestHighLevelClient client(){
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(
                        // 本地demo快速實作效果,host等資訊直接寫成固定值了,
                        new HttpHost("toutou.com",9200,"http")
                )
        );
        return client;
    }
}

5.3 根據id查詢城市酒店資訊

5.3.1 添加Service

CityEsService:

import java.util.Map;

/**
 * @author toutou
 * @date by 2021/02
 * @des
 */
public interface  CityEsService {
    Map<String,Object> getCityById(String id);
}

iceCityEsService

CityEsServiceImpl:

package learn.service.impl;

import learn.service.CityEsService;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author toutou
 * @date by 2021/02
 * @des
 */
@Service
public class CityEsServiceImpl implements CityEsService{
    @Autowired
    private RestHighLevelClient client;

    @Override
    public Map<String,Object> getCityById(String id){
        GetRequest getRequest=new GetRequest("city","_doc",id);
        Map map=new HashMap();
        GetResponse response=null;
        try{
            response= client.get(getRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(response.isExists()){
            // 本初為了方便演示,將id回傳
            map.put("id", response.getId());

            // 默認不回傳id資訊,若不需要id資訊直接回傳getSource結果即可,
            map.putAll(response.getSource());
            return map;
        }else{
            throw new RuntimeException("Is not exists.");
        }
    }
}

5.3.2 添加Controller

/**
 * @author toutou
 * @date by 2021/2
 * @des   https://www.cnblogs.com/toutou
 */
@Slf4j
@RestController
public class IndexController {

    @Autowired
    private CityEsService cityEsService;


    @GetMapping("es/search")
    public Result esSearch(@RequestParam("id") String id) {
        return Result.setSuccessResult(cityEsService.getCityById(id));
    }
}

5.3.3 效果驗證

由于service層和Controller大部分代碼都是重復的,下面就只貼service層代碼實作了,感興趣的可以在文章底部的原始碼中查看更多細節,

5.4 根據id洗掉城市酒店資訊

5.4.1 洗掉方法實作代碼

    @Override
    public String delCityById(String id){
        try {
            DeleteRequest request=new DeleteRequest("city","_doc",id);
            DeleteResponse response= client.delete(request,RequestOptions.DEFAULT);
            return response.status().name();
        } catch (IOException e) {
            throw new RuntimeException("洗掉失敗.");
        }
    }

5.4.2 效果驗證

5.5 添加資料

    @Override
    public String addCityByInfo(String id, String name, Integer level, String address, String createTime){
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("name", name);
        jsonMap.put("level", level);
        jsonMap.put("address", address);
        jsonMap.put("createTime", createTime);

        // 若不需要創建指定id的資料,則不需要再IndexRequest的建構式中傳入id
        // IndexRequest indexRequest = new IndexRequest("city", "_doc");
        IndexRequest indexRequest = new IndexRequest("city", "_doc", id);
        indexRequest.source(jsonMap);
        try {
            IndexResponse rp = client.index(indexRequest);
            return rp.status().name();
        } catch (IOException e) {
            throw new RuntimeException("添加失敗.");
        }
    }

5.6 修改資料

    @Override
    public String updateCityByInfo(String id, String name){
        UpdateRequest request=new UpdateRequest("city","_doc", id);
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("name", name);
        request.doc(jsonMap);
        try {
            return client.update(request,RequestOptions.DEFAULT).status().name();
        } catch (IOException e) {
            throw new RuntimeException("修改失敗.");
        }
    }

5.7 復合查詢

    public List<Map<String, Object>> query(String name, Integer level, Integer index, Integer size){
        SearchRequest request = new SearchRequest("city");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("name", name));
        boolQueryBuilder.must(QueryBuilders.matchQuery("level", level));
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //排序
        searchSourceBuilder.sort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC));
        //分頁
        searchSourceBuilder.from(index).size(size).query(boolQueryBuilder);
        request.searchType(SearchType.DEFAULT).source(searchSourceBuilder);
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            SearchResponse rp = client.search(request, RequestOptions.DEFAULT);
            for (SearchHit item : rp.getHits().getHits()) {
                list.add(item.getSourceAsMap());
            }
        } catch (IOException e) {
            throw new RuntimeException("查詢失敗.");
        }

        return list;
    }

其他參考資料:

  • Elasticsearch: 權威指南
  • elasticsearch - Docker Hub
  • Java High Level REST Client

v原始碼地址

https://github.com/toutouge/javademosecond/tree/master/hellospringboot


作  者:請叫我頭頭哥
出  處:http://www.cnblogs.com/toutou/
關于作者:專注于基礎平臺的專案開發,如有問題或建議,請多多賜教!
著作權宣告:本文著作權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文鏈接,
特此宣告:所有評論和私信都會在第一時間回復,也歡迎園子的大大們指正錯誤,共同進步,或者直接私信我
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角【推薦】一下,您的鼓勵是作者堅持原創和持續寫作的最大動力!

<style>#comment_body_3242240 { display: none }</style>

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/438610.html

標籤:Java

上一篇:C語言程式設計100例之(75):Vigenère 密碼

下一篇:反射、靜態代理、動態代理(jdk、cglib)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more