扩展词库

对于某些特定行业的词语在词库中没有这样的词语,我们可以通过扩展词库来实现

比如凯悦这个词语,在行业内我们希望这是以一个词语的形式出现,但实际情况IK分词器却不如人意

GET /operation/_analyze{ "analyzer": "ik_smart", "text": "凯悦"}

结果

{ "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 } ]}

这样我们就需要进行词库的扩展,具体方法如下

进入容器

docker exec -it es(容器名称) /bin/bash

进入ES的插件文件夹(plugins)

cd plugins

因为我们安装插件的时候在该文件中创建了IK文件夹,具体安装可以移步:https://blog.51cto.com/9844951/2472968

cd ik/config

创建新文件以存放扩展词语

vi new_wore.dic

在IK分词器的配置文件中加入该文件IKAnalyzer.cfg.xml,用于ES加载使用

<?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"></entry> <!--用户可以在这里配置自己的扩展停止词字典--><entry key="ext_stopwords"></entry><!--用户可以在这里配置远程扩展字典 --><!-- <entry key="remote_ext_dict">words_location</entry> --><!--用户可以在这里配置远程扩展停止词字典--><!-- <entry key="remote_ext_stopwords">words_location</entry> --></properties>

上面内容是IK分词器自带的配置文件,我们只需要在扩展字典处配置进去新建扩展词文件即可

<?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">new_word.dic</entry> <!--用户可以在这里配置自己的扩展停止词字典--><entry key="ext_stopwords"></entry><!--用户可以在这里配置远程扩展字典 --><!-- <entry key="remote_ext_dict">words_location</entry> --><!--用户可以在这里配置远程扩展停止词字典--><!-- <entry key="remote_ext_stopwords">words_location</entry> --></properties>

修改好后保存文件、退出容器,重启容器

如果是集群环境将修改好的文件复制到宿主机后,再发送到不同的服务器,再传递到容器中

具体docker操作命令可以移步:https://blog.51cto.com/9844951/2469349

服务间拷贝资料命令

scp IKAnalyzer.cfg.xml root@IP(要拷贝到目的服务器IP):/usr/local/

当然,如果集群服务器间做了SSL后就不需要输入密码之类的

文件一切就绪后重启ES容器

重启后我们可以验证一下

GET /operation/_analyze{ "analyzer": "ik_smart", "text": "凯悦"}

结果

{ "tokens" : [ { "token" : "凯悦", "start_offset" : 0, "end_offset" : 2, "type" : "CN_WORD", "position" : 0 } ]}

正是我们想要的结果

此处在通过凯悦二字搜索文档时将会没有任何结果,效果如下:

{ "took" : 38, "timed_out" : false, "_shards" : { "total" : 3, "successful" : 3, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 0, "relation" : "eq" }, "max_score" : null, "hits" : [ ] }}

hits没有任何文档