ElasticSearch5.0——IK词库加载

来源:互联网 发布:linux编辑文本查找命令 编辑:程序博客网 时间:2024/06/05 23:57


Dictionary Configuration
IKAnalyzer.cfg.xml can be located at {conf}/analysis-ik/config/IKAnalyzer.cfg.xml or {plugins}/elasticsearch-analysis-ik-*/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">custom/mydict.dic;custom/single_word_low_freq.dic</entry>     <!--用户可以在这里配置自己的扩展停止词字典-->    <entry key="ext_stopwords">custom/ext_stopword.dic</entry>    <!--用户可以在这里配置远程扩展字典 -->    <entry key="remote_ext_dict">location</entry>    <!--用户可以在这里配置远程扩展停止词字典-->    <entry key="remote_ext_stopwords">http://xxx.com/xxx.dic</entry></properties>
热更新 IK 分词使用方法
目前该插件支持热更新 IK 分词,通过上文在 IK 配置文件中提到的如下配置
    <!--用户可以在这里配置远程扩展字典 -->    <entry key="remote_ext_dict">location</entry>    <!--用户可以在这里配置远程扩展停止词字典-->    <entry key="remote_ext_stopwords">location</entry>
其中 location 是指一个 url,比如 http://yoursite.com/getCustomDict,该请求只需满足以下两点即可完成分词热更新。
该 http 请求需要返回两个头部(header),一个是 Last-Modified,一个是 ETag,这两者都是字符串类型,只要有一个发生变化,该插件就会去抓取新的分词进而更新词库。
该 http 请求返回的内容格式是一行一个分词,换行符用 \n 即可。

满足上面两点要求就可以实现热更新分词了,不需要重启 ES 实例。

还需要注意的是获取词典的url,必须支持head访问

下面自己做的访问远程扩展词典的web api 服务接口

        [HttpHead, HttpGet, HttpPost]        public async Task<HttpResponseMessage> GetDictionary(string path)        {            var response = this.Request.CreateResponse(HttpStatusCode.OK);            var content = File.ReadAllText(path);            response.Content = new StringContent(content, Encoding.UTF8);            response.Headers.Age = TimeSpan.FromHours(1);            response.Headers.ETag = EntityTagHeaderValue.Parse($"\"{content.ToMD5()}\"");            return response;        }

其中参数path为文件实际的地址。文件存储的数据格式是一行一个词。

配置文件添加远程扩展字典实例如下:

<?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">custom/mydict.dic;custom/single_word_low_freq.dic</entry> <!--用户可以在这里配置自己的扩展停止词字典--><entry key="ext_stopwords">custom/ext_stopword.dic</entry><!--用户可以在这里配置远程扩展字典 --><entry key="remote_ext_dict">http://ip:port/API/GetDictionaryTest/GetDictionary?path=C:/elasticsearch-5.0.0/config/ik/custom/mydict.txt</entry> 


注意路径的分隔符,使用反斜杠‘/’

可以将需自动更新的热词放在一个 UTF-8 编码的 .txt 文件里,放在 nginx 或其他简易 http server 下,当 .txt 文件修改时,http server 会在客户端请求该文件时自动返回相应的 Last-Modified 和 ETag。可以另外做一个工具来从业务系统提取相关词汇,并更新这个 .txt 文件。
1 0
原创粉丝点击