【Elasticsearch】Elasticsearch 6.x 探索之路-中文分詞器IK
阿新 • • 發佈:2019-02-06
1.分詞機制
Elasticsearch對於查詢,是採取按分詞的結果進行查詢的,作為一款非國產的軟體,自然對於中文的查詢支援並不是很好,預設只會把中文拆分成單字,而通常使用都是以“詞”作為基準單位的。
我們可以使用外掛(plugins)機制去拓展Elasticsearch的分詞器(analyzer)
2.中文分詞器-IK
IK是常用的一款中文分詞外掛
有兩種方法安裝外掛
2.1方法一:直接將外掛相關檔案放到es的plugins資料夾下
路徑示例:
/usr/share/elasticsearch/plguins/ik
2.2方法二:使用es提供的elasticsearch plugin install
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.3.0/elasticsearch-analysis-ik-6.3.0.zip
其中的6.3.0是es的版本號
3.使用
安裝外掛後,直接重啟es即可自動載入
systemctl stop elasticsearch.service
systemctl start elasticsearch.service
我們建立一個index並在mappings配置中指定分詞器為IK
$ curl -X PUT 'localhost:9200/news' -d ' { "mappings": { "new": { "properties": { "content": { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_max_word" } } } } }'
以下使用IK上的示例
curl -XPOST http://localhost:9200/news/new/1 -H 'Content-Type:application/json' -d'
{"content":"美國留給伊拉克的是個爛攤子嗎"}
'
curl -XPOST http://localhost:9200/news/new/2 -H 'Content-Type:application/json' -d'
{"content":"公安部:各地校車將享最高路權"}
'
curl -XPOST http://localhost:9200/news/new/3 -H 'Content-Type:application/json' -d' {"content":"中韓漁警衝突調查:韓警平均每天扣1艘中國漁船"} '
curl -XPOST http://localhost:9200/news/new/4 -H 'Content-Type:application/json' -d'
{"content":"中國駐洛杉磯領事館遭亞裔男子槍擊 嫌犯已自首"}
'
進行查詢
curl -XPOST http://localhost:9200/news/new/_search -H 'Content-Type:application/json' -d'
{
"query" : { "match" : { "content" : "中國" }},
"highlight" : {
"pre_tags" : ["<tag1>", "<tag2>"],
"post_tags" : ["</tag1>", "</tag2>"],
"fields" : {
"content" : {}
}
}
}
'
結果:
{
"took": 14,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 2,
"hits": [
{
"_index": "index",
"_type": "new",
"_id": "4",
"_score": 2,
"_source": {
"content": "中國駐洛杉磯領事館遭亞裔男子槍擊 嫌犯已自首"
},
"highlight": {
"content": [
"<tag1>中國</tag1>駐洛杉磯領事館遭亞裔男子槍擊 嫌犯已自首 "
]
}
},
{
"_index": "index",
"_type": "new",
"_id": "3",
"_score": 2,
"_source": {
"content": "中韓漁警衝突調查:韓警平均每天扣1艘中國漁船"
},
"highlight": {
"content": [
"均每天扣1艘<tag1>中國</tag1>漁船 "
]
}
}
]
}
}