ES——中文分词以及词库扩展
中文分词插件的安装:
elasticserch默认情况下是不支持中文分词的,所以在我们日常的开发中需要安装下中文词库的插件analysis-ik。
首先进入elasticsearch的根目录下执行以下命令安装插件,版本要和自己电脑安装的elasticsearch版本对应上,如本人电脑安装的是6.6.1版本:
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.6.1/elasticsearch-analysis-ik-6.6.1.zip
检查下中文分词是否生效——
标准分词
GET _analyze?pretty{"analyzer": "standard","text":"中华人民共和国国歌"}
智能分词
GET _analyze?pretty{"analyzer": "ik_smart","text":"中华人民共和国国歌"}
最大化分词
GET _analyze?pretty{"analyzer": "ik_max_smart","text":"中华人民共和国国歌"}
最佳实践:索引建立时使用最大化分词,查询时使用智能分词
词库扩展
接下来就是词库的扩展,词库扩展主要对应中文字典中不存在的词汇进行添加,如网络用语中的“骚年”,公司的名称等等都是词库扩展的主要对象。除此之外,我们词库扩展还有同义词的扩展,如我们平常用的iphone,当输入“苹果”的时候,我们也是期待能查出手机的。所以这里说的词库扩展主要分两项,其一是生词扩展,二是同义词扩展
一、中文词库扩展:
1.新增词库
cd /elasticsearch-6.6.1/config/analysis-ik
新建文件new_word.dic
vim new_word.dic
骚年阿里巴巴百度
2.配置词库,重启elasticsearch
cd elasticsearch-6.6.1/config/analysis-ik
配置词库路径,默认是配置文件的相对路径,配置如下
<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>
3.通过_update_by_query 更新索引,使词库生效(不建议暴力重新建索引)
#加了新词库更新
POST /shop/_update_by_query{"query": {"bool": {"must": [{"term": { "name":"骚" }},{"term": { "name":"年" }}]}}}
二、中文同义词扩展:
1.新增同义词词库
cd /elasticsearch-7.9.1/config/analysis-ik
vim synonyms.txt
苹果,iphone
2.重新建立索引,设置自定义分词analysis
PUT /shop{"settings": {"number_of_shards": 1,"number_of_replicas": 0,"analysis": {"filter": {"synonym_filter":{"type": "synonym","synonyms_path":"analysis-ik/synonyms.txt"}},"analyzer": {"ik_syno":{"type":"custom","tokenizer":"ik_smart","filter":["synonym_filter"]},"ik_syno_max":{"type":"custom","tokenizer":"ik_max_word","filter":["synonym_filter"]}}}},"mappings": {"properties": {"id":{"type":"integer"},"name":{"type":"text","analyzer": "ik_syno_max","search_analyzer": "ik_syno"},"tags":{"type":"text","analyzer": "whitespace","fielddata": true},"location":{"type":"geo_point"},"remark_score":{"type":"double"},"price_per_man":{"type":"integer"},"category_id":{"type":"integer"},"category_name":{"type":"keyword"},"seller_id":{"type":"integer"},"seller_remark_score":{"type":"double"},"seller_disabled_flag":{"type":"integer"}}}}
