1、ElasticSearch簡介
ElasticSearch是一個基于Lucene的開源搜尋引擎,通過簡單的RESTful API來隐藏Lucene的複雜性。全文搜尋,分析系統,分布式資料庫。
ElasticSearch類似于關系型資料庫,儲存資料是以檔案形式儲存,自身建立一套索引以及算法,提高查詢效率和速度
2、安裝環境準備步驟
-
檢查伺服器jdk是否安裝
cmd 輸入指令 java -version
2)檢查伺服器是否有node環境(檢視ElasticSearch可視化界面需要,非必須)
cmd 輸入 node -v
3)準備各個元件(本文對非必須元件暫無資料)
Elasticsearch(搜尋引擎的主要元件,必須安裝)
下載下傳位址:https://www.elastic.co/cn/downloads/elasticsearch 目前最新版本7.7.0
analysis-ik(目前對中文分詞支援最完善的插件,搜尋中文内容建議安裝)
下載下傳位址:https://github.com/medcl/elasticsearch-analysis-ik/releases 目前最新版本7.7.0
logstash(搜尋引擎同步資料庫資料元件,項目非分布式資料庫或多個搜尋引擎就非必須安裝)
下載下傳位址:https://www.elastic.co/cn/downloads/past-releases
elasticsearch-head(搜尋引擎資料可視化界面,非必須)
下載下傳位址:https://github.com/mobz/elasticsearch-head
Kibana(搜尋引擎資料統計可視化元件,非必須)
下載下傳位址:https://www.elastic.co/cn/downloads/kibana 目前最新版本7.7.0
-
Elasticsearch
Elasticsearch下載下傳後解壓。
運作解壓後的bin目錄中的elasticsearch.bat
在cmd界面Ctrl+C即可退出服務;
另外,在生産環境下,建議用elasticsearch-service.bat,運作elasticsearch-service.bat install,将其安裝成系統服務。
浏覽器輸入:http://127.0.0.1:9200 檢視效果
可根據項目情況修改name、cluster_name等資訊,該名字用于後續整合springboot配置
-
analysis-ik
analysis-ik下載下傳後解壓。
把解壓後的内容拷貝至elasticsearch-7.7.0\plugins目錄下,重新開機elasticsearch即可。
-
整合ElasticSearch + springboot
建立一個springboot項目
pom添加elasticsearch依賴
<!-- 添加 spring-data-elasticsearch的依賴 -->
<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
</dependency>
application.yml添加配置
在spring.data節點下添加一下配置
elasticsearch:
cluster-name: gis-es #一開始配置elasticsearch內建名稱
cluster-nodes: localhost:9300 #預設提供給springboot的節點端口為9300,http為9200
repositories:
enabled: true
首先,在需要查詢的model上添加注解
Document:文檔,等同于關系型資料庫表中的行。
IndexName:索引名稱
type:類型,可以了解成關系資料庫中Table
第二,建立Repository類繼承ElasticsearchRepository
從源碼可以看出該類繼承了CRUDRepository,是以對應的接口不止搜尋功能,還有增删改的功能,具體實作可根據自身業務再進一步探索
最後,在service層中注入repository
在需要使用的方法中直接使用即可,類似持久層DAO的使用。
6、在具體項目中設定分詞器
springboot項目啟動後,在elasticsearch的檢索庫中就會建立對應的文檔,文檔索引名為XXX_index,就是注解Document的indexName。
第一步:通過使用postman關閉索引
在postman執行post請求
http://localhost:9200/XXX_index/_close
第二步:通過使用postman設定分詞器
在postman執行PUT請求
http://localhost:9200/XXX_index/_settings?preserve_existing=true
body中json參數
{
"index":
{ "analysis":
{"analyzer":
{"default":
{
"type":"ik_smart" #"ik_max_word"
}
}
}
}
}
第三步:通過使用postman開啟索引
在postman執行post請求
http://localhost:9200/XXX_index/_open