1.ik分词器简介
IK分词器的两种分词模式:
模式 | 备注 |
---|---|
ik_max_word | 会将文本做最细粒度的拆分,比如会将"中华人民共和国国歌"拆分为"中华人民共和国,中华人民,中华,华人,人民共和国,人民,人,民,共和国,共和,和,国国,国歌",会穷尽各种可能的组合; |
ik_smart | 会做最粗粒度的拆分,比如会将"中华人民共和国国歌"拆分为"中华人民共和国,国歌"。 |
2.IK分词器安装
这里我们采用在线安装的方式:注意安装的版本必须与es一致。
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.7.0/elasticsearch-analysis-ik-6.7.0.zip
3.创建索引
分配3个主分片和一个复制分片(每个主分片都有一个复制分片),设置映射规则。
PUT http://10.168.14.40:8200/yrz
{
"settings" : {
"number_of_shards" : 3,
"number_of_replicas" : 1
}
"mappings":{
"company_info":{
"properties":{
"title":{
"type":"keyword"
},
"desc":{
"type":"text",
"analyzer": "ik_max_word"
}
}
}
}
}
yrz:为索引名称,company_info:为索引对应的type;
number_of_shards:3 分配3个主分片,number_of_replicas:1 分配一个复制分片;
为desc字段指定了analyzer,就是一个自定义分词器。为text类型的字段会被进行分词,然后索引;而keyword类型字段不会被分词。
3.查看分词效果
POST http://10.xxx.xx.40:8200/_analyze
{
"text":"中华人民共和国国歌",
"analyzer":"ik_max_word"
}
分词效果如下:
{
"tokens": [
{
"token": "中华人民共和国",
"start_offset": 0,
"end_offset": 7,
"type": "CN_WORD",
"position": 0
},
{
"token": "中华人民",
"start_offset": 0,
"end_offset": 4,
"type": "CN_WORD",
"position": 1
},
{
"token": "中华",
"start_offset": 0,
"end_offset": 2,
"type": "CN_WORD",
"position": 2
},
{
"token": "华人",
"start_offset": 1,
"end_offset": 3,
"type": "CN_WORD",
"position": 3
},
{
"token": "人民共和国",
"start_offset": 2,
"end_offset": 7,
"type": "CN_WORD",
"position": 4
},
{
"token": "人民",
"start_offset": 2,
"end_offset": 4,
"type": "CN_WORD",
"position": 5
},
{
"token": "共和国",
"start_offset": 4,
"end_offset": 7,
"type": "CN_WORD",
"position": 6
},
{
"token": "共和",
"start_offset": 4,
"end_offset": 6,
"type": "CN_WORD",
"position": 7
},
{
"token": "国",
"start_offset": 6,
"end_offset": 7,
"type": "CN_CHAR",
"position": 8
},
{
"token": "国歌",
"start_offset": 7,
"end_offset": 9,
"type": "CN_WORD",
"position": 9
}
]
}
4.IK自定义分词词库配置
进入es安装目录,config文件下找到ik插件安装目录/elasticsearch-6.7.0/config/analysis-ik。
新增自定义词库文件yrz.dic
中华人民共和国
国歌
修改IK配置文件 IKAnalyzer.cfg.xml ,添加自定义词库。
$ vim IKAnalyzer.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>IK Analyzer 扩展配置</comment>
<!--用户可以在这里配置自己的扩展字典 -->
<entry key="ext_dict">yrz.dic</entry>
<!--用户可以在这里配置自己的扩展停止词字典-->
<entry key="ext_stopwords"></entry>
<!--用户可以在这里配置远程扩展字典 -->
<!-- <entry key="remote_ext_dict">words_location</entry> -->
<!--用户可以在这里配置远程扩展停止词字典-->
<!-- <entry key="remote_ext_stopwords">words_location</entry> -->
</properties>
完成后重启es集群。
我们再看下分词效果
POST http://10.xxx.xx.40:8200/_analyze
{
"text":"中华人民共和国国歌",
"analyzer":"ik_smart"
}
{
"tokens": [
{
"token": "中华人民共和国",
"start_offset": 0,
"end_offset": 7,
"type": "CN_WORD",
"position": 0
},
{
"token": "国歌",
"start_offset": 7,
"end_offset": 9,
"type": "CN_WORD",
"position": 1
}
]
}