ElasticSearch5.0——IK词库加载

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

[html] 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">  
  3. <properties>  
  4.     <comment>IK Analyzer 扩展配置</comment>  
  5.     <!--用户可以在这里配置自己的扩展字典 -->  
  6.     <entry key="ext_dict">custom/mydict.dic;custom/single_word_low_freq.dic</entry>  
  7.      <!--用户可以在这里配置自己的扩展停止词字典-->  
  8.     <entry key="ext_stopwords">custom/ext_stopword.dic</entry>  
  9.     <!--用户可以在这里配置远程扩展字典 -->  
  10.     <entry key="remote_ext_dict">location</entry>  
  11.     <!--用户可以在这里配置远程扩展停止词字典-->  
  12.     <entry key="remote_ext_stopwords">http://xxx.com/xxx.dic</entry>  
  13. </properties>  

热更新 IK 分词使用方法
目前该插件支持热更新 IK 分词,通过上文在 IK 配置文件中提到的如下配置

[html] 
  1. <!--用户可以在这里配置远程扩展字典 -->  
  2. <entry key="remote_ext_dict">location</entry>  
  3. <!--用户可以在这里配置远程扩展停止词字典-->  
  4. <entry key="remote_ext_stopwords">location</entry>  

其中 location 是指一个 url,比如 http://yoursite.com/getCustomDict,该请求只需满足以下两点即可完成分词热更新。
该 http 请求需要返回两个头部(header),一个是 Last-Modified,一个是 ETag,这两者都是字符串类型,只要有一个发生变化,该插件就会去抓取新的分词进而更新词库。
该 http 请求返回的内容格式是一行一个分词,换行符用 即可。

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

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

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

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


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

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

[html] 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">  
  3. <properties>  
  4.     <comment>IK Analyzer 扩展配置</comment>  
  5.     <!--用户可以在这里配置自己的扩展字典 -->  
  6.     <entry key="ext_dict">custom/mydict.dic;custom/single_word_low_freq.dic</entry>  
  7.      <!--用户可以在这里配置自己的扩展停止词字典-->  
  8.     <entry key="ext_stopwords">custom/ext_stopword.dic</entry>  
  9.     <!--用户可以在这里配置远程扩展字典 -->  
  10.     <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 文件。

原文地址:https://www.cnblogs.com/a-du/p/7602536.html