ElasticSearch7.X.X-初見-模仿京東搜索的實戰
- 2021 年 10 月 9 日
- 筆記
- JAVA, elasticsearch, kuang-項目
這裡是ElasticSearch7.X.X+模仿京東搜索的實戰 的學習筆記,6.X與7.X區別還是挺大的。
簡介
Elaticsearch,簡稱為ES,ES是一個開源的高擴展的分散式全文檢索引擎,它可以近乎實時的存儲、檢索數據;本身擴展性很好,可以擴展到上百台伺服器,處理 PB 級別(大數據時代)的數據。
ES由 Java 語言開發並使用 Lucene 作為其核心來實現所有索引和搜索的功能,但是它的目的是通過簡單的 RESTFULL API 來隱藏 Lucene 的複雜性,從而讓全文搜索變得簡單。
聊聊Doug Cutting
1998年9月4日,Google公司在美國矽谷成立,正如大家所知,它是一家做搜索引擎起家的公司
無獨有偶,一位名叫Doug Cutting的美國工程師,也迷上了搜索引擎。他做了一個用於文本搜索的函數庫(姑且理解為軟體的功能組件),命名為Lucene。
Lucene是用JAVA寫成的,目標是為各種中小型應用軟體加入全文檢索功能。因為好用而且開源,非常受程式設計師們的歡迎。
早期的時候,這個項目被發布在Doug Cutting的個人網站和SourceForge (一個開源軟體網站)。後來,2001年底,Lucene成為Apache軟體基金會jakarta項目的一個子項目。
2004年,Doug Cutting再接再勵,在Lucene的基礎上,和Apache開源夥伴Mike Cafarella合作,開發了一款可以代替當時的主流搜索的開源搜索引擎,命名為Nutch。
Lucene 是一套資訊檢索工具包,jar包,不包含搜索引擎系統。
包含的:索引結構,讀寫索引的工具,排序,搜索規則…工具類。
Lucene和ElasticSearch關係
ElasticSearch是基於Lucene做了一些封裝和增強(上手簡單)。
ES&Solr&Lucene
Elasticsearch簡介
Elasticsearch是一個實時分散式搜索和分析引擎。它讓你以前所未有的速度處理大數據成為可能。它用於全文搜索、結構化搜索、分析以及將這三者混合使用︰
維基百科使用Elasticsearch提供全文搜索並高亮關鍵字,以及輸入實時搜索(search-asyou-type)和搜索糾錯(did-you-mean)等搜索建議功能。
英國衛報使用Elasticsearch結合用戶日誌和社交網路數據提供給他們的編輯以實時的回饋,以便及時了解公眾對新發表的文章的回應。
StackOverflow結合全文搜索與地理位置查詢,以及more-like-this功能來找到相關的問題和答案。Github使用Elasticsearch檢索1300億行的程式碼。
但是Elasticsearch不僅用於大型企業,它還讓像DataDog以及Klout這樣的創業公司將最初的想法變成可擴展的解決方案。Elasticsearch可以在你的筆記型電腦上運行,也可以在數以百計的伺服器上處理PB級別的數據。
Elasticsearch是一個基於Apache Lucene™的開源搜索引擎。無論在開源還是專有領域,Lucene可以被認為是迄今為止最先進、性能最好的、功能最全的搜索引擎庫。
但是,Lucene只是一個庫。想要使用它,你必須使用Java來作為開發語言並將其直接集成到你的應用中,更糟糕的是, Lucene非常複雜,你需要深入了解檢索的相關知識來理解它是如何工作的。
Elasticsearch也使用Java開發並使用Lucene作為其核心來實現所有索引和搜索的功能,但是它的目的是通過簡單的RESTful API來隱藏Lucene的複雜性,從而讓全文搜索變得簡單。
Solr簡介
Solr是Apache下的一個頂級開源項目,採用Java開發,它是基於Lucene的全文搜索伺服器。Solr提供了比Lucene更為豐富的查詢語言,同時實現了可配置、可擴展,並對索引、搜索性能進行了優化
Solr可以獨立運行,運行在)Tomcat等這些Servlet容器中,Solr索引的實現方法很簡單,用POST方法向Solr伺服器發送一個描述Field及其內容的XML文檔,Solr根據xml文檔添加、刪除、更新索引。Solr搜索只需要發送HTTP GET請求然後對 Solr返回Xml,json等格式的查詢結果進行解析,組織頁面布局。Solr不提供構建UI的功能,Solr提供了一個管理介面,通過管理介面可以查詢Solr的配置和運行情況。
Solr是基於lucene開發企業級搜索伺服器,實際上就是封裝了lucene。
Solr是一個獨立的企業級搜索應用伺服器,它對外提供類似於Web-service的APlI介面。用戶可以通過http請求,向搜索引擎伺服器提衣一定格式的文件,牛成索引:也可以通討提出杳找請求,並得到返回結果
Lucene簡介
Lucene是apache軟體基金會 jakarta項目組的一個子項目,是一個開放源程式碼的全文檢索引擎工具包,但它不是一個完整的全文檢索引擎,而是一個全文檢索引擎的架構,提供了完整的查詢引擎和索引引擎,部分文本分析引擎(英文與德文兩種西方語言)。Lucene的目的是為軟體開發人員提供一個簡單易用的工具包,以方便的在目標系統中實現全文檢索的功能,或者是以此為基礎建立起完整的全文檢索引擎。Lucene是一套用於全文檢索和搜尋的開源程式庫,由Apache軟體基金會支援和提供。Lucene提供了一個簡單卻強大的應用程式介面,能夠做全文索引和搜尋。在Java開發環境里Lucene是一個成熟的免費開源工具。就其本身而言,Lucene是當前以及最近幾年最受歡迎的免費Java資訊檢索程式庫。人們經常提到資訊檢索程式庫,雖然與搜索引擎有關,但不應該將資訊檢索程式庫與搜索引擎相混淆。
Lucene是一個全文檢索引擎的架構。那什麼是全文搜索引擎?
全文搜索引擎是名副其實的搜索引擎,國外具代表性的有Google、Fast/AliTheWeb、AltaVista、Inktomi、Teoma、WiseNut等,中國著名的有百度(Baidu )。它們都是通過從互聯網上提取的各個網站的資訊(以網頁文字為主)而建立的資料庫中,檢索與用戶查詢條件匹配的相關記錄,然後按一定的排列順序將結果返回給用戶,因此他們是真正的搜索引擎。
從搜索結果來源的角度,全文搜索引擎又可細分為兩種,一種是擁有自己的檢索程式(Indexer ),俗稱"蜘蛛" ( Spider )程式或"機器人" ( Robot)程式,並自建網頁資料庫,搜索結果直接從自身的資料庫中調用,如上面提到的7家引擎;另一種則是租用其他引擎的資料庫,並按自定的格式排列搜索結果,如Lycos引擎。
總結
1、ES基本是開箱即用,非常簡單。Solr安裝略微複雜一丟丟!
2、Solr利用Zookeeper進行分散式管理,而Elasticsearch自身帶有分散式協調管理功能。
3、Polr支援更多格式的數據,比如ISON、XML、CSV,而Elasticsearch僅支援json文件格式。
4、Solr官方提供的功能更多,而Elasticsearch本身更注重於核心功能,高級功能多有第三方插件提供,例如圖形化介面需要kibana友好支撐。
5、Solr查詢快,但更新索引時慢(即插入刪除慢),用於電商等查詢多的應用。
- ES建立索引快(即查詢慢),即實時性查詢快,用於facebook新浪等搜索。
- Solr是傳統搜索應用的有力解決方案,但Elasticsearch更適用於新興的實時搜索應用。
6、Solr比較成熟,有一個更大,更成熟的用戶、開發和貢獻者社區,而Elasticsearch相對開發維護者較少,更新太快,學習使用成本較高。
ES的安裝
下載地址://www.elastic.co/cn/downloads/elasticsearch
Version:
7.15.0
Release date:
September 23, 2021
Downloads:
熟悉目錄
bin 啟動文件
config 配置文件
log4j 日誌配置文件
jvm.options java虛擬機相關的配置
elasticSearch.yml ElasticSearch的配置文件 默認9200埠
lib 相關jar包
logs 日誌
modules 功能模組
plugins 插件
點擊bin文件夾中的bat就可以啟動了,然後訪問//127.0.0.1:9200/就可以看到
{
"name" : "DESKTOP-KFAD8D1",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "K8DWmnQISdetKLrPlwchJQ",
"version" : {
"number" : "7.15.0",
"build_flavor" : "default",
"build_type" : "zip",
"build_hash" : "79d65f6e357953a5b3cbcc5e2c7c21073d89aa29",
"build_date" : "2021-09-16T03:05:29.143308416Z",
"build_snapshot" : false,
"lucene_version" : "8.9.0",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
安裝可視化介面ES head插件
下載地址://github.com/mobz/elasticsearch-head
前提需要npm, 該目錄下安裝依賴npm install 也可以用cnpm install
啟動測試npm run start(在這個目錄裡面cmd:D:\java_env\elasticsearch-head-master\elasticsearch-head-master)
再訪問//localhost:9100/就可以看到:
由於跨域問題 需要進行配置 config/elsaticsearch.yml
使用Easticsearc時侯啟動時,點擊elasticsearch.bat發生閃退。
原因:允許elasticsearch跨越訪問時,在修改了elasticsearch的配置文件,並且以非UTF-8的格式修改的,結果就報錯了。
http.cors.enabled: true
http.cors.allow-origin: "*"
初學時可以把ES當做一個資料庫(可以建立索引 (庫) ,文檔 (庫中的數據) )
這個head 我們就把它當做數據展示工具 我們後面所有的查詢都用Kibana
了解ELK
ELK是Elasticsearch、Logstash、Kibana三大開源框架首字母大寫簡稱。市面上也被成為Elastit Stack。其中Elasticsearch是一個基於Lucene、分散式、通過Restful方式進行交互的近實時搜索平台框架。像類似百度、Google這種大數據全文搜索引擎的場景都可以使用Elasticsearch作為底層支援框架,可見Elasticsearch提供的搜索能力確實強大,市面上很多時候我們簡稱Elasticsearch為ES。Logstash是ELK的中央數據流引擎,用於從不同目標(文件/數據存儲/MQ)收集的不同格式數據,經過過濾後支援輸出到不同目的地(文件/MQ/redis/elasticsearch/kafka等 )。Kibana可以將elasticsearch的數據通過友好的頁面展示出來,提供實時分析的功能。
市面上很多開發只要提到ELK能夠一致說出它是一個日誌分析架構技術棧總稱,但實際上ELK不僅僅適用於日誌分析,它還可以支援其它任何數據分析和收集的場景,日誌分析和收集只是更具有代表性。並非唯一性。
安裝Kibana
Kibana是一個針對Elasticsearch的開源分析及可視化平台,用來搜索、查看交互存儲在Elasticsearch索引中的數據。使用Kibana ,可以通過各種圖表進行高級數據分析及展示。Kibana讓海量數據更容易理解。它操作簡單,基於瀏覽器的用戶介面可以快速創建儀錶板( dashboard ) 實時顯示Elasticsearch查詢動態。設置Kibana非常簡單。無需編碼或者額外的基礎架構,幾分鐘內就可以完成Kibana安裝並啟動Elasticsearch索引監測。
官網//www.elastic.co/cn/downloads/kibana
Kibana 版本要和 Es一致,埠5601
好處:ELK都是基本上拆箱即用。
Version:
7.15.0
Release date:
September 23, 2021
Downloads:
我們之後的所有的操作都在這裡編寫://localhost:5601/app/dev_tools#/console
這個項目做了國際化,所以在Kibana.yml中改為 i18n.locale: "zh-CN"就可以了。
ES核心概念
- 索引
- 欄位類型(mapping)
- 文檔(documents)
ElasticSearch是面向文檔,關係行資料庫和elasticsearch客觀的對比 一切都是JSON
| Relational DB | ElasticSearch |
|---|---|
| DataBase | indicate |
| tables | type,慢慢在棄用 |
| rows | documents |
| columns | fields |
ElasticSearch(集群)中可以包含多個索引(資料庫),每個索引中可以包含多個類型(表),每個類型下又包含多個文檔行),每個文檔中又包含多個欄位(列)。
物理設計:
ElasticSearch在後台把每個索引劃分成多個分片,每分分片可以在集群中的不同伺服器間遷移
一個人就是一個集群,默認的集群名稱就是ElasticSearch。
邏輯設計∶
一個索引類型中,包含多個文檔,比如說文檔1,文檔2。當我們索引一篇文檔時,可以通過這樣的一各順序找到它:索引》類型文檔ID,通過這個組合我們就能索引到某個具體的文檔。注意:ID不必是整數,實際上它是個字元串。
文檔
之前說ElasticSearch是面向文檔的,那麼就意味著索引和搜索數據的最小單位是文檔,ElasticSearch中,文檔有幾個重要屬性︰
- 自我包含,一篇文檔同時包含欄位和對應的值,也就是同時包含key:value !
- 可以是層次型的,一個文檔中包含自文檔,複雜的邏輯實體就是這麼來的!
- 靈活的結構,文檔不依賴預先定義的模式,我們知道關係型資料庫中,要提前定義欄位才能使用,在ElasticSearch中,對於欄位是非常靈活的,有時候,我們可以忽略該欄位,或者動態的添加一個新的欄位。
儘管我們可以隨意的新增或者忽略某個欄位,但是,每個欄位的類型非常重要,比如一個年齡欄位類型,可以是字元串也可以是整形。因為ElasticSearch會保存欄位和類型之間的映射及其他的設置。這種映射具體到每個映射的每種類型,這也是為什麼在ElasticSearch中,類型有時候也稱為映射類型。
類型
類型是文檔的邏輯容器,就像關係型資料庫一樣,表格是行的容器。類型中對於欄位的定義稱為映射,比如name映射為字元串類型。我們說文檔是無模式的,它們不需要擁有映射中所定義的所有欄位,比如新增一個欄位,那麼elasticsearch是怎麼做的呢?elasticsearch會自動的將新欄位加入映射,但是這個欄位的不確定它是什麼類型,elasticsearch就開始猜,如果這個值是18,那麼elasticsearch會認為它是整形。但是elasticsearch也可能猜不對,所以最安全的方式就是提前定義好所需要的映射,這點跟關係型資料庫殊途同歸了,先定義好欄位,然後再使用。
索引
就是資料庫
索引是映射類型的容器, ElasticSearch中的索引是一個非常大的文檔集合。索引存儲了映射類型的欄位和其他設置。然後它們被存儲到了各個分片上了。
物理設計︰節點和分片如何工作
一個集群至少有一個節點,而一個節點就是一個ElasticSearch進程,節點可以有多個索引默認的,如果你創建索引,那麼索引將會有個5個分片( primary shard ,又稱主分片)構成的,每一個主分片會有一個副本( replica shard ,又稱複製分片) 。
上圖是一個有3個節點的集群,可以看到主分片和對應的複製分片都不會在同一個節點內,這樣有利於某個節點掛掉了,數據也不至於丟失。實際上,一個分片是一個Lucene索引,一個包含倒排索引的文件目錄,倒排索引的結構使得 ElasticSearch 在不掃描全部文檔的情況下,就能告訴你哪些文檔包含特定的關鍵字。
倒排索引
ElasticSearch 使用的是一種稱為倒排索引的結構,採用Lucene倒排索作為底層。這種結構適用於快速的全文搜索,一個索引文檔中所有不重複的列表構成,對於每一個詞,都有一個包含它的文檔列表。
例如,現在有兩個文檔,每個文檔包含如下內容∶
Study every day,good good up to forever # 文檔1包含的內容
To forever, study every day, good good up # 文檔2包含的內容
為了創建倒排索引,我們首先要將每個文檔拆分成獨立的詞(或稱為詞條或者tokens),然後創建一個包含所有不重複的詞條的排序列表,然後列出每個詞條出現在哪個文檔:
現在,我們試圖搜索to forever,只需要查看包含每個詞條的文檔
兩個文檔都匹配,但是第一個文檔比第二個匹配程度更高。如果沒有別的條件,現在,這兩個包含關鍵字的文檔都將返回。
ElasticSearch 的索引和Lucene的索引對比
在ElasticSearch 中,索引(庫)這個詞被頻繁使用,這就是術語的使用。在ElasticSearch 中,索引被分為多個分片,每份分片是一個Lucene的索引。所以一個ElasticSearch 索引是由多個Lucene索引組成的。別問為什麼,誰讓elasticElasticSearch search使用Lucene作為底層呢!如無特指,說起索引都是指ElasticSearch 的索引。
接下來的一切操作都在kibana中Dev Tools下的Console里完成。
IK分詞器插件
如果要使用中文,建議使用ik分詞器
IK提供了兩個分詞演算法: ik smart和ik_max_word,其中ik_smart為最少切分, ik_max_word為最細粒度劃分!
- 下載://github.com/medcl/elasticsearch-analysis-ik/releases
- 下載完畢後,放入我們的ElasticSearch插件中即可
- 重啟觀察ES
- elasticsearch-plugin list可以通過這個命令來查看載入進來的插件
- 使用Kibana測試
查看不同的分詞效果
ik_smart為最少切分
GET _analyze
{
"analyzer": "ik_smart",
"text": "中國我愛你"
}
{
"tokens" : [
{
"token" : "中國",
"start_offset" : 0,
"end_offset" : 2,
"type" : "CN_WORD",
"position" : 0
},
{
"token" : "我愛你",
"start_offset" : 2,
"end_offset" : 5,
"type" : "CN_WORD",
"position" : 1
}
]
}
ik_max_word為最細粒度劃分,窮盡詞庫的可能
GET _analyze
{
"analyzer": "ik_max_word",
"text": "中國我愛你"
}
{
"tokens" : [
{
"token" : "中國",
"start_offset" : 0,
"end_offset" : 2,
"type" : "CN_WORD",
"position" : 0
},
{
"token" : "我愛你",
"start_offset" : 2,
"end_offset" : 5,
"type" : "CN_WORD",
"position" : 1
},
{
"token" : "愛你",
"start_offset" : 3,
"end_offset" : 5,
"type" : "CN_WORD",
"position" : 2
}
]
}
ik分詞器增加自己的配置
GET _analyze
{
"analyzer": "ik_smart",
"text": "我愛你貝貝子"
}
{
"tokens" : [
{
"token" : "我愛你",
"start_offset" : 0,
"end_offset" : 3,
"type" : "CN_WORD",
"position" : 0
},
{
"token" : "貝",
"start_offset" : 3,
"end_offset" : 4,
"type" : "CN_CHAR",
"position" : 1
},
{
"token" : "貝子",
"start_offset" : 4,
"end_offset" : 6,
"type" : "CN_WORD",
"position" : 2
}
]
}
但是貝貝子是一個名字,所以我要把她加入到字典中。
{
"tokens" : [
{
"token" : "我愛你",
"start_offset" : 0,
"end_offset" : 3,
"type" : "CN_WORD",
"position" : 0
},
{
"token" : "貝貝子",
"start_offset" : 3,
"end_offset" : 6,
"type" : "CN_WORD",
"position" : 1
}
]
}
Rest風格說明
一種軟體架構風格,而不是標準,只是提供了一組設計原則和約束條件。它主要是用於客戶端和伺服器交互類的軟體。基於這個風格設計的軟體可以更簡潔,更有層次,更易於實現快取等機制。
基本Rest命令說明:
關於索引的基本操作
PUT /索引名/~索引名(未來可能取消不寫)~/文檔id
{請求體}
PUT /test1/type1/1
{
"name": "lijiatu",
"age": 12
}
{
"_index" : "test1",
"_type" : "type1",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
數據就成功添加了
數據類型
-
字元串類型
text, keyword
-
數值類型
long, integer, short, byte, double, float, half float, scaled fload
-
日期類型
date
-
布爾值類型
boolean
-
二進位類型
binart
-
等等…
指定欄位的類型
PUT /test2
{
"mappings": {
"properties": {
"name": {
"type": "text"
},
"age": {
"type": "long"
},
"birthday": {
"type": "date"
}
}
}
}
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "test2"
}
獲得這個規則資訊, 可以通過GET請求獲取具體的資訊
GET test2
{
"test2" : {
"aliases" : { },
"mappings" : {
"properties" : {
"age" : {
"type" : "long"
},
"birthday" : {
"type" : "date"
},
"name" : {
"type" : "text"
}
}
},
"settings" : {
"index" : {
"routing" : {
"allocation" : {
"include" : {
"_tier_preference" : "data_content"
}
}
},
"number_of_shards" : "1",
"provided_name" : "test2",
"creation_date" : "1633697875995",
"number_of_replicas" : "1",
"uuid" : "SxOsgsKGR0CYM9Lejh4FWg",
"version" : {
"created" : "7150099"
}
}
}
}
}
============================================================
PUT test3/_doc/1
{
"name": "lijiatu",
"age": 12
}
{
"_index" : "test3",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
==========================================================
GET test3
{
"test3" : {
"aliases" : { },
"mappings" : {
"properties" : {
"age" : {
"type" : "long"
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
},
"settings" : {
"index" : {
"routing" : {
"allocation" : {
"include" : {
"_tier_preference" : "data_content"
}
}
},
"number_of_shards" : "1",
"provided_name" : "test3",
"creation_date" : "1633698204680",
"number_of_replicas" : "1",
"uuid" : "ElIym67sQySiOW1AKCyJ9Q",
"version" : {
"created" : "7150099"
}
}
}
}
}
如果自己的文檔欄位沒有指定,那麼es就會給我們默認配置欄位類型!
通過get _cat/ 可以獲得當前的很多資訊。
修改 提交還是使用PUT即可,然後覆蓋值,或用新辦法。
PUT test3/_doc/1
{
"name": "lijiatubeibeizi",
"age": 12
}
{
"_index" : "test3",
"_type" : "_doc",
"_id" : "1",
"_version" : 2,版本號增加了
"result" : "updated",修改
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1
}
或者使用post來更新
POST test3/_doc/1
{
"doc": {
"name": "beibeizi"
}
}
{
"_index" : "test3",
"_type" : "_doc",
"_id" : "1",
"_version" : 3,版本號增加了
"result" : "updated",修改
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 3,
"_primary_term" : 1
}
刪除索引
通過DELETE命令實現刪除, 根據你的請求來判斷是刪除索引還是刪除文檔記錄
DELETE test1
{
"acknowledged" : true
}
使用RESTFUL風格是我們ES推薦大家使用的。
關於文檔的基本操作(重點)
添加數據
PUT lijiatu/test/1
{
"name": "lijiatu",
"age": 21,
"desc": "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags": ["二次元","宅男","碼農"]
}
PUT lijiatu/test/2
{
"name": "beibeizi",
"age": 21,
"desc": "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags": ["二次元","女","碼農"]
}
獲取數據
GET lijiatu/test/1
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "lijiatu",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"宅男",
"碼農"
]
}
}
更新數據
PUT lijiatu/test/3
{
"name": "beibeizi333",
"age": 21,
"desc": "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags": ["二次元","女","碼農"]
}
POST _update,推薦使用這種修改方式
複雜操作-搜索
GET lijiatu/test/1
也可以帶條件查詢
GET lijiatu/test/_search?q=name:lijiatu
{
"took" : 57,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.2039728,
"hits" : [
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "1",
"_score" : 1.2039728,
"_source" : {
"name" : "lijiatu",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"宅男",
"碼農"
]
}
}
]
}
}
簡單的條件查詢,可以根據默認的映射規則,產生基本的查詢。
**複雜查詢 (排序,分頁,高亮,模糊查詢,精準查詢等) **
GET lijiatu/test/_search
{
"query": {
"match": {
"name": "李嘉圖"
}
}
}
{
"took" : 583,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 0.43278474,
"hits" : [
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "1",
"_score" : 0.43278474,
"_source" : {
"name" : "李嘉圖",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"女",
"碼農"
]
}
},
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "2",
"_score" : 0.38623023,
"_source" : {
"name" : "李嘉圖2",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"女",
"碼農"
]
}
},
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "3",
"_score" : 0.38623023,
"_source" : {
"name" : "李嘉圖3",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"女",
"碼農"
]
}
}
]
}
}
hit :
索引和文檔的資訊
查詢的結果總數
然後就是查詢出來的具體的文檔
數據中的東西都可以遍歷出來了
分數:我們可以通過來判斷誰更加更加符合結果
結果過濾
GET lijiatu/test/_search
{
"query": {
"match": {
"name": "李嘉圖"
}
},
"_source": ["name","age"]
}
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 0.43278474,
"hits" : [
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "1",
"_score" : 0.43278474,
"_source" : {
"name" : "李嘉圖",
"age" : 21
}
},
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "2",
"_score" : 0.38623023,
"_source" : {
"name" : "李嘉圖2",
"age" : 21
}
},
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "3",
"_score" : 0.38623023,
"_source" : {
"name" : "李嘉圖3",
"age" : 21
}
}
]
}
}
排序
GET lijiatu/test/_search
{
"query": {
"match": {
"name": "李嘉圖"
}
},
"sort": [
{
"age": {
"order": "desc"
}
}
]
}
{
"took" : 5,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "1",
"_score" : null,
"_source" : {
"name" : "李嘉圖",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"女",
"碼農"
]
},
"sort" : [
21
]
},
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "2",
"_score" : null,
"_source" : {
"name" : "李嘉圖2",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"女",
"碼農"
]
},
"sort" : [
21
]
},
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "3",
"_score" : null,
"_source" : {
"name" : "李嘉圖3",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"女",
"碼農"
]
},
"sort" : [
21
]
}
]
}
}
分頁查詢
GET lijiatu/test/_search
{
"query": {
"match": {
"name": "李嘉圖"
}
},
"sort": [
{
"age": {
"order": "desc"
}
}
],
"from": 0,
"size": 2
}
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "1",
"_score" : null,
"_source" : {
"name" : "李嘉圖",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"女",
"碼農"
]
},
"sort" : [
21
]
},
{
"_index" : "lijiatu",
"_type" : "test",
"_id" : "2",
"_score" : null,
"_source" : {
"name" : "李嘉圖2",
"age" : 21,
"desc" : "願你擁有大風與烈酒,也能享受孤獨與自由",
"tags" : [
"二次元",
"女",
"碼農"
]
},
"sort" : [
21
]
}
]
}
}
數據下標還是從0開始
布爾值查詢
must (and) 所有的條件都要符合 相當於 where id = 1 and name = xxx
GET lijiatu/test/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"name": "李"
}
},
{
"match": {
"age": 21
}
}
]
}
}
}
should (or) 所有的條件符合其一 相當於 where id = 1 or name = xxx
GET lijiatu/test/_search
{
"query": {
"bool": {
"should": [
{
"match": {
"name": "李"
}
},
{
"match": {
"age": 21
}
}
]
}
}
}
must_not (not) 反向查詢
GET lijiatu/test/_search
{
"query": {
"bool": {
"must_not": [
{
"match": {
"age": 21
}
}
]
}
}
}
過濾器 filter
"filter": [
{}
]
gt 大於
gte 大於等於
lt 小於
lte 小於等於
匹配多個條件
GET lijiatu/test/_search
{
"query": {
"match": {
"tags": "男 碼農"
}
}
}
多個條件使用空格隔開
只要滿足其中一個結果既可以被查出
這個時候可以通過分值基本的判斷
精確查詢
term 查詢是直接通過倒排索引指定的詞條進程精確的查找的
關於分詞:
- term,直接查詢精確的
- match, 會使用分詞器解析 (先分析文檔,然後通過分析的文檔進行查詢)
兩個類型 text keyword
GET _analyze
{
"analyzer": "keyword",
"text": ["李嘉圖"]
}
沒有被拆分
{
"tokens" : [
{
"token" : "李嘉圖",
"start_offset" : 0,
"end_offset" : 3,
"type" : "word",
"position" : 0
}
]
}
GET _analyze
{
"analyzer": "standard",
"text": "李嘉圖"
}
拆分了
{
"tokens" : [
{
"token" : "李",
"start_offset" : 0,
"end_offset" : 1,
"type" : "<IDEOGRAPHIC>",
"position" : 0
},
{
"token" : "嘉",
"start_offset" : 1,
"end_offset" : 2,
"type" : "<IDEOGRAPHIC>",
"position" : 1
},
{
"token" : "圖",
"start_offset" : 2,
"end_offset" : 3,
"type" : "<IDEOGRAPHIC>",
"position" : 2
}
]
}
多個值匹配的精確查詢
bool should term
高亮查詢
GET lijiatu/test/_search
{
"query": {
"match": {
"name": "李嘉圖"
}
},
"highlight": {
"pre_tags": "<p class='key' style='color:red'>",
"post_tags": "</p>",
"fields": {
"name": {}
}
}
}
集成SpringBoot
項目地址://gitee.com/zwtgit/elastic-search-jing-dong-and-apistudy
找到原生的依賴
<repositories>
<repository>
<id>es-snapshots</id>
<name>elasticsearch snapshot repo</name>
<url>//snapshots.elastic.co/maven/</url>
</repository>
</repositories>
然後就是要注意導入SpringBoot項目後ES的版本不一致的問題。
例如我導入後:
所以要相應的修改一下
快速開始,使用 源碼中提供的對象
package com.zwt.esapi.config;
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;
//Spring倆個步驟 1.找對象 2.放到Spring中
@Configuration
public class ESConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1",9200,"http")
)
);
return client;
}
}
具體的API測試
- 創建索引
- 判斷索引是否存在
- 刪除索引
- 創建文檔
- CRUD文檔
關於索引的API操作
@Autowired
@Qualifier("restHighLevelClient") //不加也行 但定義的名字要是這個名字
private RestHighLevelClient client;
//測試索引的創建 Request PUT lijiatu_index
@Test
void testCreateIndex() throws IOException {
//1. 創建索引請求
CreateIndexRequest request = new CreateIndexRequest("lijiatu_index");
//2. 客戶端執行請求
CreateIndexResponse createIndexRequest = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexRequest);
}
//測試獲取索引,判斷其是否存在
@Test
void testExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("lijiatu_index");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
//測試刪除索引
@Test
void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("lijiatu_index");
//刪除
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
關於文檔的API操作
//測試添加文檔
@Test
void testAddDocument() throws IOException {
//創建對象
User user = new User("李嘉圖", 12);
//創建請求
IndexRequest request = new IndexRequest("ahui_index");
//規則 put lijiatu_index/_doc/1
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
//將我們的數據放入請求 json (使用fastjson進行轉換)
IndexRequest source = request.source(JSON.toJSONString(user), XContentType.JSON);
//客戶端發送請求, 獲取響應的結果
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
//返回具體的json資訊
System.out.println(indexResponse.toString());
//對應我們命令返回的狀態 CREATED
System.out.println(indexResponse.status());
}
//獲取文檔
@Test
void testIsExistes() throws IOException {
GetRequest getRequest = new GetRequest("lijiatu_index", "1");
//不獲取返回的_source 的上下文了
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
//獲取文檔的資訊
@Test
void testGetDocument() throws IOException {
GetRequest getRequest = new GetRequest("lijiatu_index", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
//列印文檔的內容
System.out.println(getResponse.getSourceAsString());
//返回的全部內容和命令是一樣的
System.out.println(getResponse);
}
//獲取文檔的資訊
@Test
void testUpdateRequest() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("lijiatu_index", "1");
updateRequest.timeout("1s");
User user = new User("李嘉圖學Java", 22);
updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
}
//刪除文檔記錄
@Test
void testDeleteRequest() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("lijiatu_index", "1");
deleteRequest.timeout("1s");
DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.status());
}
//特殊的,實際項目中一般都會批量插入數據
@Test
void testBulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userList = new ArrayList<>();
userList.add(new User("lijiatu1", 18));
userList.add(new User("lijiatu1", 18));
userList.add(new User("lijiatu1", 18));
userList.add(new User("lijiatu1", 18));
userList.add(new User("lijiatu1", 18));
userList.add(new User("lijiatu1", 18));
//批量處理請求
for (int i = 0; i < userList.size(); i++) {
//批量更新和批量修改等, 就在這裡修改對應的請求就可以了
bulkRequest.add(new IndexRequest("ahui_index")
.id("" + (i + 1)) //不加id的話會默認生成隨機id
.source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
//是夠失敗, 返回false代表成功
System.out.println(bulkResponse.hasFailures());
}
//查詢
//SearchRequest 搜索請求
//SearchSourceBuilder 條件構造
//HighLightBuilder 構建高亮
//xxx QueryBuilder 對應我們剛才看到的所有命令
@Test
void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("lijiatu_index");
//構建搜索條件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//查詢條件,我們可以使用QueryBuilders 工具類來實現
//QueryBuilders.termQuery 精確匹配
//QueryBuilders.matchAllQuery 匹配所有
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "lijiatu");
// MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse.getHits()));
System.out.println("==========================================");
for (SearchHit documentFileds : searchResponse.getHits().getHits()) {
System.out.println(documentFileds.getSourceAsMap());
}
}
源碼
@Import({ RestClientConfigurations.RestClientBuilderConfiguration.class,
RestClientConfigurations.RestHighLevelClientConfiguration.class,
RestClientConfigurations.RestClientFallbackConfiguration.class })
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.elasticsearch.rest;
import java.time.Duration;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Elasticsearch rest client infrastructure configurations.
*
* @author Brian Clozel
* @author Stephane Nicoll
*/
class RestClientConfigurations {
@Configuration(proxyBeanMethods = false)
static class RestClientBuilderConfiguration {
@Bean
@ConditionalOnMissingBean
RestClientBuilder elasticsearchRestClientBuilder(RestClientProperties properties,
ObjectProvider<RestClientBuilderCustomizer> builderCustomizers) {
HttpHost[] hosts = properties.getUris().stream().map(HttpHost::create).toArray(HttpHost[]::new);
RestClientBuilder builder = RestClient.builder(hosts);
PropertyMapper map = PropertyMapper.get();
map.from(properties::getUsername).whenHasText().to((username) -> {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials(properties.getUsername(),
properties.getPassword());
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
builder.setHttpClientConfigCallback(
(httpClientBuilder) -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
});
builder.setRequestConfigCallback((requestConfigBuilder) -> {
map.from(properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMillis)
.to(requestConfigBuilder::setConnectTimeout);
map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis)
.to(requestConfigBuilder::setSocketTimeout);
return requestConfigBuilder;
});
builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return builder;
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RestHighLevelClient.class)
static class RestHighLevelClientConfiguration {
@Bean
@ConditionalOnMissingBean
RestHighLevelClient elasticsearchRestHighLevelClient(RestClientBuilder restClientBuilder) {
return new RestHighLevelClient(restClientBuilder);
}
@Bean
@ConditionalOnMissingBean
RestClient elasticsearchRestClient(RestClientBuilder builder,
ObjectProvider<RestHighLevelClient> restHighLevelClient) {
RestHighLevelClient client = restHighLevelClient.getIfUnique();
if (client != null) {
return client.getLowLevelClient();
}
return builder.build();
}
}
@Configuration(proxyBeanMethods = false)
static class RestClientFallbackConfiguration {
@Bean
@ConditionalOnMissingBean
RestClient elasticsearchRestClient(RestClientBuilder builder) {
return builder.build();
}
}
}
京東搜索實戰
項目地址://gitee.com/zwtgit/elastic-search-jing-dong-and-apistudy
項目導入靜態資源後:
數據爬取京東的首頁,可以看之前的爬蟲小項目爬取數據
爬蟲項目地址://www.cnblogs.com/zwtblog/p/15216808.html
具體的業務編寫
package com.zwt.service;
import com.alibaba.fastjson.JSON;
import com.zwt.pojo.Content;
import com.zwt.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class ContentService {
@Autowired
private RestHighLevelClient restHighLevelClient;
//1.解析數據 放入 ES 索引中
public Boolean parseContent(String ketwords) throws IOException {
List<Content> contents = new HtmlParseUtil().parseJD(ketwords);
//把查詢出來的數據放入 ES中
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("2m");
for (int i = 0; i < contents.size(); i++) {
bulkRequest.add(
new IndexRequest("jd_goods")
.source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
);
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulk.hasFailures();
}
//2.獲取這些數據 實現搜索功能
public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
if (pageNo <= 1) {
pageNo = 1;
}
//條件搜索
SearchRequest searchRequest = new SearchRequest("jd_goods");
SearchSourceBuilder searcheBuilder = new SearchSourceBuilder();
//分頁
searcheBuilder.from(pageNo);
searcheBuilder.size(pageSize);
//精準匹配
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
searcheBuilder.query(termQueryBuilder);
searcheBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//執行搜索
searchRequest.source(searcheBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//解析結果
ArrayList<Map<String, Object>> list = new ArrayList<>();
for (SearchHit documentFields : searchResponse.getHits().getHits()) {
list.add(documentFields.getSourceAsMap());
}
return list;
}
}
package com.zwt.controller;
import com.zwt.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
import java.util.Map;
//請求編寫
@RestController
public class ContentController {
@Autowired
private ContentService contentService;
@GetMapping("/parse/{keyword}")
public Boolean parse(@PathVariable("keyword") String keyword) throws Exception {
return contentService.parseContent(keyword);
}
@GetMapping("/search/{keyword}/{pageNo}/{pageSize}")
public List<Map<String, Object>> search(@PathVariable("keyword") String keyword,
@PathVariable("pageNo") int pageNo,
@PathVariable("pageSize") int pageSize) throws IOException {
return contentService.searchPage(keyword, pageNo, pageSize);
}
}
業務基本編寫完成,準備進行前後端交換
最後實現「高亮」
效果圖

