es學習(三):分詞器介紹以及中文分詞器ik的安裝與使用
阿新 • • 發佈:2020-02-09
什麼是分詞
把文字轉換為一個個的單詞,分詞稱之為analysis。es預設只對英文語句做分詞,中文不支援,每個中文字都會被拆分為獨立的個體。
示例
POST http://192.168.247.8:9200/_analyze { "analyzer":"standard", "text":"good good study" } # 返回 { "tokens": [ { "token": "good", "start_offset": 0, "end_offset": 4, "type": "<ALPHANUM>", "position": 0 }, { "token": "good", "start_offset": 5, "end_offset": 9, "type": "<ALPHANUM>", "position": 1 }, { "token": "study", "start_offset": 10, "end_offset": 15, "type": "<ALPHANUM>", "position": 2 } ] }
如果想在某個索引下進行分詞
POST /my_doc/_analyze
{
"analyzer": "standard",
"field": "name",
"text": "text文字"
}
es內建分詞器
standard:預設分詞,單詞會被拆分,大小會轉換為小寫。
simple:按照非字母分詞。大寫轉為小寫。
whitespace:按照空格分詞。忽略大小寫。
stop:去除無意義單詞,比如the/a/an/is…
keyword:不做分詞。把整個文字作為一個單獨的關鍵詞
建立ik中文分詞器
下載
Github:https://github.com/medcl/elasticsearch-analysis-ik
這裡需要選擇和你的es版本一致的ik。我的是7.5.1
解壓
[root@localhost software]# ls elasticsearch-7.5.1-linux-x86_64.tar.gz elasticsearch-analysis-ik-7.5.1.zip [root@localhost software]# unzip elasticsearch-analysis-ik-7.5.1.zip -d /usr/local/elasticsearch-7.5.1/plugins/ik
重啟es
ik_max_word 和 ik_smart 什麼區別?
ik_max_word: 會將文字做最細粒度的拆分,比如會將“中華人民共和國國歌”拆分為“中華人民共和國,中華人民,中華,華人,人民共和國,人民,人,民,共和國,共和,和,國國,國歌”,會窮盡各種可能的組合,適合 Term Query;
ik_smart: 會做最粗粒度的拆分,比如會將“中華人民共和國國歌”拆分為“中華人民共和國,國歌”,適合 Phrase 查詢。
測試
POST http://192.168.247.8:9200/_analyze
{
"analyzer":"ik_max_word",
"text":"上下班做公交"
}
# 返回
{
"tokens": [
{
"token": "上下班",
"start_offset": 0,
"end_offset": 3,
"type": "CN_WORD",
"position": 0
},
{
"token": "上下",
"start_offset": 0,
"end_offset": 2,
"type": "CN_WORD",
"position": 1
},
{
"token": "下班",
"start_offset": 1,
"end_offset": 3,
"type": "CN_WORD",
"position": 2
},
{
"token": "做",
"start_offset": 3,
"end_offset": 4,
"type": "CN_CHAR",
"position": 3
},
{
"token": "公交",
"start_offset": 4,
"end_offset": 6,
"type": "CN_WORD",
"position": 4
}
]
}
自定義中文詞庫
1.進入IKAnalyzer.cfg.xml 配置如下
<!--使用者可以在這裡配置自己的擴充套件字典 -->
<entry key="ext_dict">custom.dic</entry>
2.儲存後 再同級目錄下建立custom.dic
[esuser@localhost config]$ cat custom.dic
崔神
牛皮
3.重啟es
4.測試
POST http://192.168.247.8:9200/_analyze
{
"analyzer":"ik_smart",
"text":"崔神牛皮"
}
# 返回
{
"tokens": [
{
"token": "崔神",
"start_offset": 0,
"end_offset": 2,
"type": "CN_WORD",
"position": 0
},
{
"token": "牛皮",
"start_offset": 2,
"end_offset": 4,
"type": "CN_WORD",
"position": 1
}
]
}