一、簡介
全文搜索屬于最常見的需求,開源的 Elasticsearch (以下簡稱 Elastic)是目前全文搜索引擎的首選。
它可以快速地儲存、搜索和分析海量數據。維基百科、Stack Overflow、Github 都采用它
Elastic 的底層是開源庫 Lucene。但是,你沒法直接用 Lucene,必須自己寫代碼去調用它的接口。Elastic 是 Lucene 的封裝,提供了 REST API 的操作接口,開箱即用。
本文從零開始,講解如何使用 Elastic 搭建自己的全文搜索引擎。每一步都有詳細的說明,大家跟著做就能學會。
二、安裝
Elastic 需要 Java 8 環境。如果你的機器還沒安裝 Java,可以參考這篇文章,注意要保證環境變量JAVA_HOME
正確設置。
安裝完 Java,就可以跟著官方文檔安裝 Elastic。直接下載壓縮包比較簡單。
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.3.2.zip
tar -zvxf elasticsearch-6.3.2.tar.gz
進入解壓后的目錄,運行下面的命令,啟動 Elastic
[root@bogon opt]# cd elasticsearch-6.3.2
[root@bogon elasticsearch-6.3.2]# ls
bin config lib LICENSE.txt logs modules NOTICE.txt plugins README.textile
[root@bogon elasticsearch-6.3.2]# ./bin/elasticsearch
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.
[2018-08-01T17:14:31,803][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [] uncaught exception in thread [main]
org.elasticsearch.bootstrap.StartupException: java.lang.RuntimeException: can not run elasticsearch as root
at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:140) ~[elasticsearch-6.3.2.jar:6.3.2]
at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:127) ~[elasticsearch-6.3.2.jar:6.3.2]
at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:86) ~[elasticsearch-6.3.2.jar:6.3.2]
at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:124) ~[elasticsearch-cli-6.3.2.jar:6.3.2]
at org.elasticsearch.cli.Command.main(Command.java:90) ~[elasticsearch-cli-6.3.2.jar:6.3.2]
at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:93) ~[elasticsearch-6.3.2.jar:6.3.2]
at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:86) ~[elasticsearch-6.3.2.jar:6.3.2]
Caused by: java.lang.RuntimeException: can not run elasticsearch as root
at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:104) ~[elasticsearch-6.3.2.jar:6.3.2]
at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:171) ~[elasticsearch-6.3.2.jar:6.3.2]
at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:326) ~[elasticsearch-6.3.2.jar:6.3.2]
at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:136) ~[elasticsearch-6.3.2.jar:6.3.2]
... 6 more
[root@bogon elasticsearch-6.3.2]#
可以看到我們啟動報錯了,找到報錯原因是不能以root身份用戶啟動elasticsearch,
java.lang.RuntimeException: can not run elasticsearch as root
這是出于系統安全考慮設置的條件。由于ElasticSearch可以接收用戶輸入的腳本并且執行,為了系統安全考慮, 建議創建一個單獨的用戶用來運行ElasticSearch。
還有另一種方法是運行時加上參數:
bin/elasticsearch -Des.insecure.allow.root=true
或者修改bin/elasticsearch,加上ES_JAVA_OPTS屬性:
ES_JAVA_OPTS="-Des.insecure.allow.root=true"
啟動成功后Elastic 就會在默認的9200端口運行。這時,打開另一個命令行窗口,請求該端口,會得到說明信息。
[root@bogon ~]# curl localhost:9200
{
"name" : "xRiHjMO",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "Ew8RjOgqT_qVk69UWuhHjQ",
"version" : {
"number" : "6.3.2",
"build_flavor" : "default",
"build_type" : "tar",
"build_hash" : "053779d",
"build_date" : "2018-07-20T05:20:23.451332Z",
"build_snapshot" : false,
"lucene_version" : "7.3.1",
"minimum_wire_compatibility_version" : "5.6.0",
"minimum_index_compatibility_version" : "5.0.0"
},
"tagline" : "You Know, for Search"
}
[root@bogon ~]#
上面代碼中,請求9200端口,Elastic 返回一個 JSON 對象,包含當前節點、集群、版本等信息。
按下 Ctrl + C,Elastic 就會停止運行。
默認情況下,Elastic 只允許本機訪問,如果需要遠程訪問,可以修改 Elastic 安裝目錄的config/elasticsearch.yml文件,去掉network.host的注釋,將它的值改成0.0.0.0,然后重新啟動 Elastic。
network.host: 0.0.0.0
上面代碼中,設成0.0.0.0讓任何人都可以訪問。線上服務不要這樣設置,要設成具體的 IP。
三、基本概念
3.1 Node 與 Cluster
Elastic 本質上是一個分布式數據庫,允許多臺服務器協同工作,每臺服務器可以運行多個 Elastic 實例。
單個 Elastic 實例稱為一個節點(node)。一組節點構成一個集群(cluster)。
3.2 Index
Elastic 會索引所有字段,經過處理后寫入一個反向索引(Inverted Index)。查找數據的時候,直接查找該索引。
所以,Elastic 數據管理的頂層單位就叫做 Index(索引)。它是單個數據庫的同義詞。每個 Index (即數據庫)的名字必須是小寫。
下面的命令可以查看當前節點的所有 Index。
$ curl -X GET 'http://localhost:9200/_cat/indices?v'
3.3 Document
Index 里面單條的記錄稱為 Document(文檔)。許多條 Document 構成了一個 Index。
Document 使用 JSON 格式表示,下面是一個例子。
{ "user": "張三", "title": "工程師", "desc": "數據庫管理" }
同一個 Index 里面的 Document,不要求有相同的結構(scheme),但是最好保持相同,這樣有利于提高搜索效率。
3.4 Type
Document 可以分組,比如weather
這個 Index 里面,可以按城市分組(北京和上海),也可以按氣候分組(晴天和雨天)。這種分組就叫做 Type,它是虛擬的邏輯分組,用來過濾 Document。
不同的 Type 應該有相似的結構(schema),舉例來說,id
字段不能在這個組是字符串,在另一個組是數值。這是與關系型數據庫的表的一個區別。性質完全不同的數據(比如products
和logs
)應該存成兩個 Index,而不是一個 Index 里面的兩個 Type(雖然可以做到)。
下面的命令可以列出每個 Index 所包含的 Type。
$ curl 'localhost:9200/_mapping?pretty=true'
根據規劃,Elastic 6.x 版只允許每個 Index 包含一個 Type,7.x 版將會徹底移除 Type。
既然我們的節點(集群)已經安裝成功并且已經啟動運行,那么下一步就是去了解如何去操作它。幸運的是,Elasticsearch提供了非常全面和強大的REST API,我們可以通過它去跟集群交互。通過API我們可以完成如下的功能:
檢查集群,節點和索引的健康狀況,狀態和統計數據
管理集群,節點和索引的數據和原數據
執行CRUD(增刪改查)操作,依靠索引進行搜索
執行高級搜索操作,比如分頁,排序,過濾,腳本化,聚集等等
檢查集群
curl -XGET ‘localhost:9200/_cat/health?v&pretty’
[root@bogon ~]# curl -XGET 'localhost:9200/_cat/health?v&pretty'
epoch timestamp cluster status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1533799189 15:19:49 elasticsearch yellow 1 1 5 5 0 0 5 0 - 50.0%
我們可以看到我們的名稱為“elasticsearch”的集群正在運行,狀態標識為green。
無論何時查看集群健康狀態,我們會得到green、yellow、red中的任何一個。
- Green : 一切運行正常(集群功能齊全)
- Yellow : 所有數據是可以獲取的,但是一些復制品還沒有被分配(集群功能齊全)
- Red :一些數據因為一些原因獲取不到(集群部分功能不可用)
注意:當一個集群處于red狀態時,它會通過可用的分片繼續提供搜索服務,但是當有未分配的分片時,你需要盡快的修復它。
另外,從上面的返回結果中我們可以看到,當我們里面沒有數據時,總共有1個節點,0個分片。注意當我們使用默認的集群名稱(elasticsearch)并且當Elasticsearch默認使用單播網絡發現在同一臺機器上的其它節點時,很可能你會在你電腦上不小心啟動不止一個節點并且他們都加入了一個集群。在這種情況下,你可能會從上面的返回結果中看到不止一個節點。
四、新建和刪除 Index
新建 Index,可以直接向 Elastic 服務器發出 PUT 請求。下面的例子是新建一個名叫weather的 Index。
$ curl -X PUT 'localhost:9200/weather'
服務器返回一個 JSON 對象,里面的acknowledged字段表示操作成功。
{
"acknowledged":true,
"shards_acknowledged":true
}
然后,我們發出 DELETE 請求,刪除這個 Index。
$ curl -X DELETE 'localhost:9200/weather'
測試如下
[root@bogon opt]# curl -X PUT 'localhost:9200/weather'
{"acknowledged":true,"shards_acknowledged":true,"index":"weather"}[root@bogon opt]# curl -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 weather Pagu9NrPSN6QJgK_XtM2Zg 5 1 0 0 1.1kb 1.1kb
[root@bogon opt]# curl -X DELETE 'localhost:9200/weather'
五、中文分詞設置
首先,安裝中文分詞插件。這里使用的是 ik,也可以考慮其他插件(比如 smartcn)。
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.3.0/elasticsearch-analysis-ik-6.3.0.zip
安裝成功的提示
[elsearch@bogon elasticsearch-6.3.0]$ ./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.3.0/elasticsearch-analysis-ik-6.3.0.zip
-> Downloading https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.3.0/elasticsearch-analysis-ik-6.3.0.zip
[=================================================] 100%
-> Installed analysis-ik
[elsearch@bogon elasticsearch-6.3.0]$
上面代碼安裝的是6.3.0版的插件,與 Elastic 6.3.0配合使用。版本一定要對應!!!
接著,重新啟動 Elastic,就會自動加載這個新安裝的插件。
然后,新建一個 Index,指定需要分詞的字段。這一步根據數據結構而異,下面的命令只針對本文。基本上,凡是需要搜索的中文字段,都要單獨設置一下。
$ curl -H "Content-Type: application/json" -X PUT 'localhost:9200/accounts' -d '
{
"mappings": {
"person": {
"properties": {
"user": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"title": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"desc": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}
}
}'
上面代碼中,首先新建一個名稱為accounts
的 Index,里面有一個名稱為person
的 Type。person
有三個字段。
- user
- title
- desc
這三個字段都是中文,而且類型都是文本(text),所以需要指定中文分詞器,不能使用默認的英文分詞器。
Elastic 的分詞器稱為 analyzer。我們對每個字段指定分詞器。
"user": { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_max_word" }
上面代碼中,analyzer
是字段文本的分詞器,search_analyzer
是搜索詞的分詞器。ik_max_word
分詞器是插件ik
提供的,可以對文本進行最大數量的分詞。
六、數據操作
6.1 新增記錄
向指定的 /Index/Type 發送 PUT 請求,就可以在 Index 里面新增一條記錄。比如,向/accounts/person發送請求,就可以新增一條人員記錄。
curl -H "Content-Type: application/json" -X PUT 'localhost:9200/accounts/person/1' -d '
{
"user": "張三",
"title": "工程師",
"desc": "數據庫管理"
}'
服務器返回的 JSON 對象,會給出 Index、Type、Id、Version 等信息。
{
"_index":"accounts",
"_type":"person",
"_id":"1",
"_version":1,
"result":"created",
"_shards":{"total":2,"successful":1,"failed":0},
"created":true
}
如果你仔細看,會發現請求路徑是/accounts/person/1,最后的1是該條記錄的 Id。它不一定是數字,任意字符串(比如abc)都可以。
新增記錄的時候,也可以不指定 Id,這時要改成 POST 請求。
$ curl -H "Content-Type: application/json" -X POST 'localhost:9200/accounts/person' -d '
{
"user": "李四",
"title": "工程師",
"desc": "系統管理"
}'
{"_index":"accounts",
"_type":"person",
"_id":"vTU79WQBOZvuL_Qb1NjI",
"_version":1,
"result":"created",
"_shards":{
"total":2,
"successful":1,
"failed":0
},
"_seq_no":1,
"_primary_term":1}
上面代碼中,向/accounts/person發出一個 POST 請求,添加一個記錄。這時,服務器返回的 JSON 對象里面,_id字段就是一個隨機字符串
注意,如果沒有先創建 Index(這個例子是accounts),直接執行上面的命令,Elastic 也不會報錯,而是直接生成指定的 Index。所以,打字的時候要小心,不要寫錯 Index 的名稱。
6.2 查看記錄
向/Index/Type/Id發出 GET 請求,就可以查看這條記錄。
curl 'localhost:9200/accounts/person/1?pretty=true'
上面代碼請求查看/accounts/person/1這條記錄,URL 的參數pretty=true表示以易讀的格式返回。
返回的數據中,found字段表示查詢成功,_source字段返回原始記錄。
{
"_index" : "accounts",
"_type" : "person",
"_id" : "1",
"_version" : 1,
"found" : true,
"_source" : {
"user" : "張三",
"title" : "工程師",
"desc" : "數據庫管理"
}
}
如果 Id 不正確,就查不到數據,found字段就是false。
$ curl 'localhost:9200/weather/beijing/abc?pretty=true'
{
"_index" : "accounts",
"_type" : "person",
"_id" : "abc",
"found" : false
}
5.3 刪除記錄
刪除記錄就是發出 DELETE 請求。
$ curl -X DELETE 'localhost:9200/accounts/person/1'
這里先不要刪除這條記錄,后面還要用到。
6.4 更新記錄
更新記錄就是使用 PUT 請求,重新發送一次數據。
$ curl -X PUT 'localhost:9200/accounts/person/1' -d '
{
"user" : "張三",
"title" : "工程師",
"desc" : "數據庫管理,軟件開發"
}'
{
"_index":"accounts",
"_type":"person",
"_id":"1",
"_version":2,
"result":"updated",
"_shards":{"total":2,"successful":1,"failed":0},
"created":false
}
上面代碼中,我們將原始數據從"數據庫管理"改成"數據庫管理,軟件開發"。 返回結果里面,有幾個字段發生了變化。
"_version" : 2,
"result" : "updated",
"created" : false
可以看到,記錄的 Id 沒變,但是版本(version)從1變成2,操作類型(result)從created變成updated,created字段變成false,因為這次不是新建記錄。
七、數據查詢
7.1 返回所有記錄
使用 GET 方法,直接請求/Index/Type/_search
,就會返回所有記錄。
$ curl 'localhost:9200/accounts/person/_search' { "took":2, "timed_out":false, "_shards":{"total":5,"successful":5,"failed":0}, "hits":{ "total":2, "max_score":1.0, "hits":[ { "_index":"accounts", "_type":"person", "_id":"AV3qGfrC6jMbsbXb6k1p", "_score":1.0, "_source": { "user": "李四", "title": "工程師", "desc": "系統管理" } }, { "_index":"accounts", "_type":"person", "_id":"1", "_score":1.0, "_source": { "user" : "張三", "title" : "工程師", "desc" : "數據庫管理,軟件開發" } } ] } }
上面代碼中,返回結果的 took
字段表示該操作的耗時(單位為毫秒),timed_out
字段表示是否超時,hits
字段表示命中的記錄,里面子字段的含義如下。
total
:返回記錄數,本例是2條。max_score
:最高的匹配程度,本例是1.0
。hits
:返回的記錄組成的數組。
返回的記錄中,每條記錄都有一個_score
字段,表示匹配的程序,默認是按照這個字段降序排列。
6.2 全文搜索
Elastic 的查詢非常特別,使用自己的查詢語法,要求 GET 請求帶有數據體。
$ curl 'localhost:9200/accounts/person/_search' -d ' { "query" : { "match" : { "desc" : "軟件" }} }'
上面代碼使用 Match 查詢,指定的匹配條件是desc
字段里面包含"軟件"這個詞。返回結果如下。
{ "took":3, "timed_out":false, "_shards":{"total":5,"successful":5,"failed":0}, "hits":{ "total":1, "max_score":0.28582606, "hits":[ { "_index":"accounts", "_type":"person", "_id":"1", "_score":0.28582606, "_source": { "user" : "張三", "title" : "工程師", "desc" : "數據庫管理,軟件開發" } } ] } }
Elastic 默認一次返回10條結果,可以通過size
字段改變這個設置。
$ curl 'localhost:9200/accounts/person/_search' -d ' { "query" : { "match" : { "desc" : "管理" }}, "size": 1 }'
上面代碼指定,每次只返回一條結果。
還可以通過from
字段,指定位移。
$ curl 'localhost:9200/accounts/person/_search' -d ' { "query" : { "match" : { "desc" : "管理" }}, "from": 1, "size": 1 }'
上面代碼指定,從位置1開始(默認是從位置0開始),只返回一條結果。
6.3 邏輯運算
如果有多個搜索關鍵字, Elastic 認為它們是or
關系。
$ curl 'localhost:9200/accounts/person/_search' -d ' { "query" : { "match" : { "desc" : "軟件 系統" }} }'
上面代碼搜索的是軟件 or 系統
。
如果要執行多個關鍵詞的and
搜索,必須使用布爾查詢。
$ curl 'localhost:9200/accounts/person/_search' -d ' { "query": { "bool": { "must": [ { "match": { "desc": "軟件" } }, { "match": { "desc": "系統" } } ] } } }'
七、其他命令