SpringBoot集成Elasticsearch7.4 實戰(一)

來源:https://www.jianshu.com/p/1fbfde2aefa5

一、SpringBoot集成Elasticsearch7.4 實戰(一):這些操作都是在CentOS下操作的,主要帶大家熟悉下Elasticsearch環境。

  • 1.1.下載& Linux下ElasticSearch安裝
  • 1.2.中文分詞插件IK
  • 1.3.索引
  • 1.4.如何數據管理

二、SpringBoot集成Elasticsearch7.4 實戰(二):在Springboot環境下,利用JAVA環境操作索引。

  • 2.1.新增索引
  • 2.2.查詢索引
  • 2.3.刪除索引

三、SpringBoot集成Elasticsearch7.4 實戰(三):在Springboot環境下,管理數據。

  • 3.1.WEB HTTP提交數據<單條提交、批量提交>
  • 3.2.WEB HTTP方式條件查詢
  • 3.3.WEB HTTP刪除數據

elasticsearch

1. Linux單機安裝

題外話,這一章節僅僅作爲開發學習來構建基礎的環境,並未考慮elasticsearch的高可用性,僅說明一些基礎知識,帶大家有一個認識。當然既然是自我發揮,也就是一家之言,難免有遺漏地方,希望大家也就本着看看。

1.1. 下載&安裝

1.1.1. 環境需求

  • CentOs7
  • 內存4G+
  • JDK11+

1.1.2. 下載

 home]# wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.4.0-linux-x86_64.tar.gz

注意:elasticsearch-7.x的版本要求使用jdk11以上,如果低於jdk11,則報以下錯誤

Java HotSpot(TM) 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.

 如果自己的項目中使用的是1.8,那麼需要在服務器上安裝一個11的版本,然後將elasticsearch-7.x指定到11的版本即可

#jdk11的下載地址
home]# wget https://download.java.net/java/GA/jdk11/13/GPL/openjdk-11.0.1_linux-x64_bin.tar.gz

下載完成之後需要解壓
tar -zxvf openjdk-11.0.1_linux-x64_bin.tar.gz

指定jdk11的啓動
cd elasticseach/bin
vi elasticsearch

export JAVA_HOME=/home/jdk-11.0.1
export PATH=$JAVA_HOME/bin:$PATH

#添加jdk判斷
if [ -x "$JAVA_HOME/bin/java" ]; then
        JAVA="/home/jdk-11.0.1/bin/java"
else
        JAVA=`which java`
fi

 指定jdk11之後啓動,如果報以下錯誤

max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]

修改/etc/sysctl.conf文件,增加配置vm.max_map_count=262144
然後執行 sysctl -p 是sysctl.conf文件生效

1.1.3. 安裝

elasticsearch不允許使用root啓動,創建一個新的用戶elastic,併爲這個賬戶賦予相應的權限來啓動elasticsearch。

 


[root@localhost download]$ pwd
/data/download/

[root@localhost download]$ wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.4.0-linux-x86_64.tar.gz

[root@localhost download]$ cd ../app/

[root@localhost app]$ mkdir elastic

[root@localhost app]$ useradd elastic -g dev

[root@localhost app]$ passwd elastic

[root@localhost app]$ chown -R elastic:dev elastic

[root@localhost app]$ su elastic

[elastic@localhost app]$ cd /elastic

[elastic@localhost elastic]$ cp ../../download/elasticsearch-7.4.0-linux-x86_64.tar.gz .

[elastic@localhost elastic]$ tar -zxvf elasticsearch-7.4.0-linux-x86_64.tar.gz

[elastic@localhost elastic]$ mv elasticsearch-7.4.0/ .

1.1.4. 修改配置文件

路徑config/elasticsearch.yml

 

-- 允許外部IP訪問
network.host: 0.0.0.0

-- 把這個註釋先放開
cluster.initial_master_nodes: ["node-1", "node-2"]

-- 同時把節點的名字放開
node.name: node-1

1.1.5. 啓動&驗證結果

  • 啓動

 

[elastic@localhost elastic]$ ./bin/elasticsearch
  • 驗證結果

elastic會在默認9200端口運行,打開自己服務地址:http://192.168.147.132:9200/

啓動後驗證界面

1.1.6. 可視化工具

ElasticSearch的可視化工具有很多,比如elasticsearch-head、Dejavu、ElasticHD等。

選擇版本,下載,爲了演示需要,我用的是:

https://github.com/360EntSecGroup-Skylar/ElasticHD/releases/download/1.4/elasticHD_linux_amd64.zip

 

1、unzip elasticHD_linux_amd64.zip

2、chmod -R 777 ElasticHD

3、./ElasticHD -p 0.0.0.0:9800

ElasticHD監控

1.2. 中文分詞插件IK

1.2.1. 安裝

ik插件地址: https://github.com/medcl/elasticsearch-analysis-ik,爲了演示需要,這裏選擇wget方式。

  • 下載

 

[root@localhost download]$ wget https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.4.0/elasticsearch-analysis-ik-7.4.0.zip
  • 安裝插件

 

[elastic@localhost elastic]$ cd plugins

[elastic@localhost plugins]$ cd mkdir ik && cd ik

[elastic@localhost ik]$ cp ../../../download/elasticsearch-analysis-ik-7.4.0.zip .

[elastic@localhost ik]$ unzip elasticsearch-analysis-ik-7.4.0.zip

完成後重啓es

  • 驗證分詞器

使用crul命令,輸入下面的URL地址,驗證分詞器是否成功。

 

[elastic@localhost elastic]$ curl -X GET -H "Content-Type: application/json"  "http://localhost:9200/_analyze?pretty=true" -d'{"text":"中華五千年華夏"}';

2.png

1.2.2. ik_max_word和ik_smart

  • ik_max_word: 將文本按最細粒度的組合來拆分,比如會將“中華五千年華夏”拆分爲“五千年、五千、五千年華、華夏、千年華夏”,總之是可能的組合;

  • ik_smart: 最粗粒度的拆分,比如會將“五千年華夏”拆分爲“五千年、華夏”

不添加分詞類別,Elastic對於漢字默認使用standard只是將漢字拆分成一個個的漢字,而我們ik則更加的智能,下面通過幾個案例來說明。

1.2.2.1. ik_smart分詞

在JSON格式中添加analyzer節點內容爲ik_smart

 

[elastic@localhost elastic]$ curl -X GET -H "Content-Type: application/json"  "http://localhost:9200/_analyze?pretty=true" -d'{"text":"中華五千年華夏","analyzer": "ik_smart"}';

3.png

1.2.2.2. ik_max_word分詞

在JSON格式中添加analyzer節點內容爲ik_max_word

 

[elastic@localhost elastic]$ curl -X GET -H "Content-Type: application/json"  "http://localhost:9200/_analyze?pretty=true" -d'{"text":"中華五千年華夏","analyzer": "ik_max_word"}';

4.png

1.3. 索引

1.3.1. 創建索引

由於在ElasticSearch 7.x之後就默認不在支持指定索引類型,所以在在elasticsearch7.x上執行:

 

{
    "settings" : {
        "index" : {
            "number_of_shards" : 3, 
            "number_of_replicas" : 2 
        }
    },  
    "mappings" : {
        "twitter":{
            ......
        }
    }

執行結果則會出錯:Root mapping definition has unsupported parameters(剛開始接觸就踩了這個坑,折煞勞資好久)。如果在6.x上執行,則會正常執行。

出現這個的原因是,elasticsearch7默認不在支持指定索引類型,默認索引類型是_doc,如果想改變,則配置include_type_name: true 即可(這個沒有測試,官方文檔說的,無論是否可行,建議不要這麼做,因爲elasticsearch8後就不在提供該字段)。

https://www.elastic.co/guide/en/elasticsearch/reference/current/removal-of-types.html

1.3.1.1. 官方例子說明

 


curl -X PUT "localhost:9200/twitter" -H 'Content-Type: application/json' -d'
{
    "settings" : {
        "index" : {
            "number_of_shards" : 3, 
            "number_of_replicas" : 2 
        }
    }
}
'
  • -d指定了你的參數,這裏將這些參數放到了json文件中

  • settings設置內容含義

name 價格
number_of_shards 分片數
number_of_replicas 副本數
mappings 結構化數據設置 下面的一級屬性 是自定義的類型
properties 類型的屬性設置節點,下面都是屬性
epoch_millis 表示時間戳

1.3.1.2. 自定義索引

  • 使用json文件創建索引
    使用 -d‘@your jsonFile’指定你的json文件。下邊我創建了一個索引名稱爲product(可自己定義)的索引。

 


[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/twitter?pretty=true"  -d'@prod.json'

自定義創建索引

  • 參數形式創建索引

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/twitter?pretty=true"  -d'
{
    "settings" : {
        "index" : {
            "number_of_shards" : 3, 
            "number_of_replicas" : 2 
        }
    },  
    "mappings" : {
            "dynamic": false,
            "properties" : {
                "productid":{
                    "type" : "long"
                },  
                "name":{
                    "type":"text",
                    "index":true,
                    "analyzer":"ik_max_word"
                },  
                "short_name":{
                    "type":"text",
                    "index":true,
                    "analyzer":"ik_max_word"
                },  
                "desc":{
                    "type":"text",
                    "index":true,
                    "analyzer":"ik_max_word"
                }
            }
    }
}
'

參數形式創建索引

1.3.2. 查看索引

1.3.2.1. 全部索引

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/_cat/indices?v"
health status index   uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   twitter scSSD1SfRCio4F77Hh8aqQ   3   2          0            0       690b           690b

查看索引列表

1.3.2.2. 條件查詢

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/twitter?pretty=true"
{
  "twitter" : {
    "aliases" : { },
    "mappings" : {
      "dynamic" : "false",
      "properties" : {
        "desc" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        },
        "name" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        },
        "productid" : {
          "type" : "long"
        },
        "short_name" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        }
      }
    },
    "settings" : {
      "index" : {
        "creation_date" : "1571153735610",
        "number_of_shards" : "3",
        "number_of_replicas" : "2",
        "uuid" : "scSSD1SfRCio4F77Hh8aqQ",
        "version" : {
          "created" : "7040099"
        },
        "provided_name" : "twitter"
      }
    }
  }
}

1.3.3. 查看索引分詞器

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/twitter/_analyze?pretty=true" -d'
{
  "field": "text",
  "text": "秦皇漢武."
}
'

分詞後效果

1.3.4. 修改索引

1.3.5. 刪除索引

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X DELETE "http://localhost:9200/twitter?pretty=true"

1.4. 如何數據管理

1.4.1. 添加數據

  • 這裏演示PUT方式爲twitter索引添加數據,並且指定id,應當注意此處的默認類型爲_doc,還有一種就是採用POST方式添加數據,並且自動生成主鍵,本文就不再演示,請自行查閱相關材料。

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/twitter/_doc/1?pretty=true" -d'
{
    "productid" : 1,
    "name" : "測試添加索引產品名稱",
    "short_name" : "測試添加索引產品短標題",
    "desc" : "測試添加索引產品描述"
}
'

執行返回結果如圖,則添加數據成功。

參數形式提交數據

  • 指定id爲1,還可以加上參數op_type=create,這樣在創建重複id時會報錯導致創建失敗,否則會更新該id的屬性值。

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/twitter/_doc/1?op_type=create&pretty=true" -d'
{
    "productid" : 1,
    "name" : "測試添加索引產品名稱",
    "short_name" : "測試添加索引產品短標題",
    "desc" : "測試添加索引產品描述"
}
'

標識重複提交

1.4.2. 基礎查詢

1.4.2.1. 查詢所有

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/twitter/_search?pretty=true"

10.png

1.4.2.2. 條件查詢

條件查詢會涉及到精確詞查詢、匹配查詢、多條件查詢、聚合查詢四種,分別爲"term"、"match"、"multi_match"、"multi_match"。

  • 按找數據的名稱作爲條件查詢匹配

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/twitter/_search?pretty=true" -d'
{
    "query" : {
        "match" : { 
            "name" : "產品" 
        }
    }
}
'

11.png

  • 按找數據的標識作爲條件查詢匹配

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/twitter/_search?pretty=true" -d'
{
    "query" : {
        "match" : { 
            "productid" : 100
        }
    }
}
'

12.png

  • 多條件匹配

選擇匹配desc、short_name列作爲多條件

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/twitter/_search?pretty=true" -d'
{
    "query" : {
        "multi_match" : { 
            "query":"產品",
            "fields" : ["desc","short_name"]
        }
    }
}
'

13.png

  • 當沒有匹配任何數據適合則如下:

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/twitter/_search?pretty=true" -d'
> {
>     "query" : {
>         "match" : { 
>             "productid" : 100
>         }
>     }
> }
> '
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 3,
    "successful" : 3,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 0,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  }
}

1.4.3. 高級條件查詢

1.4.3.1. 權重boost查詢

指定一個boost值來控制每個查詢子句的相對權重,該值默認爲1。一個大於1的boost會增加該查詢子句的相對權重。
索引映射定義的時候指定boost在elasticsearch5之後已經棄用。建議在查詢的時候使用。

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/twitter/_search?pretty=true" -d'
{
    "query": {
        "match" : {
            "title": {
                "query": "quick brown fox",
                "boost": 2
            }
        }
    }
}
'

1.4.3.2. 過濾coerce查詢

數據不總是我們想要的,由於在轉換JSON body爲真正JSON 的時候,整型數字5有可能會被寫成字符串"5"或者浮點數5.0。coerce屬性可以用來清除髒數據。
一般在以下場景中:

  • 字符串會被強制轉換爲整數
  • 浮點數被強制轉換爲整數

1.4.3.2.1. 創建索引

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/wongs?pretty=true"  -d'
{
    "settings" : {
        "index" : {
            "number_of_shards" : 3, 
            "number_of_replicas" : 2 
        }
    },  
    "mappings" : {
            "properties" : {
                "col_1":{
                    "type" : "integer"
                },  
                "col_2":{
                    "type":"integer",
                    "coerce": false
                }
            }
    }
}
'

1.4.3.2.2. 創建第一個數據

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/wongs/_doc/1?pretty=true" -d'
{
    "col_1" : "20"
}
'

結果爲成功,說明col_1列數據沒問題。

1.4.3.2.3. 創建第二個數據

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/wongs/_doc/1?pretty=true" -d'
> {
>     "col_2" : "20"
> }
> '
{
  "error" : {
    "root_cause" : [
      {
        "type" : "mapper_parsing_exception",
        "reason" : "failed to parse field [col_2] of type [integer] in document with id '1'. Preview of field's value: '20'"
      }
    ],
    "type" : "mapper_parsing_exception",
    "reason" : "failed to parse field [col_2] of type [integer] in document with id '1'. Preview of field's value: '20'",
    "caused_by" : {
      "type" : "illegal_argument_exception",
      "reason" : "Integer value passed as String"
    }
  },
  "status" : 400
}

由於不能被格式化,數據新增失敗。

1.4.3.3. copy_to

copy_to允許你創造自定義超級字段_all. 也就是說,多字段的取值被複制到一個字段並且取值所有字段的取值組合, 並且可以當成一個單獨的字段查詢.
如,first_name和last_name可以合併爲full_name字段。

1.4.3.3.1. 定義索引

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/idx_copy_to?pretty=true"  -d'
{
    "settings" : {
        "index" : {
            "number_of_shards" : 3, 
            "number_of_replicas" : 2 
        }
    },  
    "mappings" : {
            "properties" : {
                "first_name":{
                    "type" : "text",
                    "copy_to": "full_name"
                },  
                "last_name":{
                    "type":"text",
                    "copy_to": "full_name"
                },
                "full_name":{
                    "type": "text"
                }
            }
    }
}
'

1.4.3.3.2. 新增數據

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/idx_copy_to/_doc/1?pretty=true" -d'
> {
>     "first_name" : "jack",
>     "last_name" : "Rose"
> }
> '
{
  "_index" : "idx_copy_to",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 3,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

1.4.3.3.3. 查詢數據

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X GET "http://localhost:9200/idx_copy_to/_search?pretty=true" -d'
{
    "query" : {
        "match": {
            "full_name": { 
                "query": "jack Rose",
                "operator": "and"
            }
        }
    }
}
'

從下圖中得知first_name和 last_name字段取值都被複制到 full_name 字段。

15.png

1.4.3.4. doc_values

是爲了加快排序、聚合操作,在建立倒排索引的時候,額外增加一個列式存儲映射,是一個空間換時間的做法。默認是開啓的,對於確定不需要聚合或者排序的字段可以關閉。

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/idx_doc_val?pretty=true"  -d'
{
    "settings" : {
        "index" : {
            "number_of_shards" : 3, 
            "number_of_replicas" : 2 
        }
    },  
    "mappings" : {
            "properties" : {
                "first_name":{
                    "type" : "text"
                },  
                "last_name":{
                    "type":"text",
                    "doc_values": false
                }
            }
    }
}
'

1.4.3.5. dynamic

默認情況下,字段可以自動添加到文檔或者文檔的內部對象,elasticsearc也會自動索引映射字段。

 

[elastic@localhost elastic]$ curl -H "Content-Type: application/json" -X PUT "http://localhost:9200/idx_dynamic?pretty=true"  -d'
{
    "settings" : {
        "index" : {
            "number_of_shards" : 3, 
            "number_of_replicas" : 2 
        }
    },  
    "mappings" : {
            "properties" : {
                "first_name":{
                    "type" : "text"
                },  
                "last_name":{
                    "type":"text",
                    "doc_values": false
                }
            }
    }
}
'

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章