安装ik分词器

官方github地址:https://github.com/medcl/elasticsearch-analysis-ik

这里需要注意的是需要下载ES对应版本的ik分词器,我这里下载的是7.6.1版本的ik分词器。下载好的ik分词器zip,解压缩后将其中的所有内容直接复制到ES文件夹的plugins/ik目录下,其中ik目录是自己创建的,然后重启ES服务即可启动ik分词器。

测试ik分词器

ik分词器有两个引擎,一个是ik_smart,还有一个是ik_max_word。启动Kibana后台,发送GET请求分别进行测试。

GET _analyze
{
  "analyzer": "ik_smart", 
  "text": "中国共产党"
}

GET _analyze
{
  "analyzer": "ik_max_word", 
  "text": "练习九阴真武功"
}

结果分别如下:

{
  "tokens" : [
    {
      "token" : "中国共产党",
      "start_offset" : 0,
      "end_offset" : 5,
      "type" : "CN_WORD",
      "position" : 0
    }
  ]
}
{
  "tokens" : [
    {
      "token" : "中国共产党",
      "start_offset" : 0,
      "end_offset" : 5,
      "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" : 2,
      "end_offset" : 5,
      "type" : "CN_WORD",
      "position" : 3
    },
    {
      "token" : "共产",
      "start_offset" : 2,
      "end_offset" : 4,
      "type" : "CN_WORD",
      "position" : 4
    },
    {
      "token" : "党",
      "start_offset" : 4,
      "end_offset" : 5,
      "type" : "CN_CHAR",
      "position" : 5
    }
  ]
}

自定义ik分词器词典

有一些单词是我们自己造的,所以ik分词器可能会不认识,这种单词如果我们想让ik分词器识别为一个单词则需要自定义字典,举个例子,比如我们想让“空卡库”成为一个单词而不是“空”、“卡”、“库”三个字则需要修改如下ik分词器的如下两个文件

  • config/IKAnalyzer.cfg.xml
  • config/yang.dir(自己新建的文件,名字随便起后缀.dir)

yang.dir的内容只有空卡库这个单词且存放于config目录下,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">my.dic</entry>
	 <!--用户可以在这里配置自己的扩展停止词字典-->
	<entry key="ext_stopwords"></entry>
	<!--用户可以在这里配置远程扩展字典 -->
	<!-- <entry key="remote_ext_dict">words_location</entry> -->
	<!--用户可以在这里配置远程扩展停止词字典-->
	<!-- <entry key="remote_ext_stopwords">words_location</entry> -->
</properties>

配置完字典前后分词效果对比:

{
  "tokens" : [
    {
      "token" : "空",
      "start_offset" : 0,
      "end_offset" : 1,
      "type" : "CN_CHAR",
      "position" : 0
    },
    {
      "token" : "卡",
      "start_offset" : 1,
      "end_offset" : 2,
      "type" : "CN_CHAR",
      "position" : 1
    },
    {
      "token" : "库",
      "start_offset" : 2,
      "end_offset" : 3,
      "type" : "CN_CHAR",
      "position" : 2
    }
  ]
}
{
  "tokens" : [
    {
      "token" : "空卡库",
      "start_offset" : 0,
      "end_offset" : 3,
      "type" : "CN_WORD",
      "position" : 0
    }
  ]
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐