elasticseach默认所有分词解析器对中文都不友好,开发建议使用Ik分词;
IK Analyzer是一个开源的,基于java语言开发的轻量级的中文分词工具包。从2006年12月推出1.0版开始, IKAnalyzer已经推出了3个大版本。最初,它是以开源项目Luence为应用主体的,结合词典分词和文法分析算法的中文分词组件。新版本的IK Analyzer 3.0则发展为面向Java的公用分词组件,独立于Lucene项目,同时提供了对Lucene的默认优化实现。
安装ik分词插件之前,前提是已经安装了es(安装步骤可参考:https://blog.csdn.net/zhanyu1/article/details/88079626),安装的ik版本和es版本也要对应, 版本对应关系详见ik主页:https://github.com/medcl/elasticsearch-analysis-ik
ik主页中有两种安装方式
optional 1 - download pre-build package from here: https://github.com/medcl/elasticsearch-analysis-ik/releases
create plugin folder cd your-es-root/plugins/ && mkdir ik
unzip plugin to folder your-es-root/plugins/ik
optional 2 - use elasticsearch-plugin to install ( supported from version v5.5.1 ):
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.3.0/elasticsearch-analysis-ik-6.3.0.zip
我们使用第一种,按照上述说明的步骤,直接下载解压即可。
安装后,plugins下,会有一个analysis-ik目录,目录下有jar包和配置文件,然后我们重启es;
接着再安装下head插件,用来测试ik分词的效果,安装步骤可参考:https://blog.csdn.net/zhanyu1/article/details/88083290
ik分词有两种ik_smart , ik_max_word,强烈建议用后者ik_max_word,分词结果很多,提高命中率;
创建index索引 put http://localhost:9200/index
创建映射
post http://localhost:9200/index/fulltext/_mapping
{
"properties": {
"content": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}
索引几个文档
post http://localhost:9200/index/fulltext/1
{"content":"美国留给伊拉克的是个烂摊子吗"}
post http://localhost:9200/index/fulltext/2
{"content":"公安部:各地校车将享最高路权"}
post http://localhost:9200/index/fulltext/3
{"content":"中韩渔警冲突调查:韩警平均每天扣1艘中国渔船"}
post http://localhost:9200/index/fulltext/4
{"content":"中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"}
然后我们来搜索测试:
post http://localhost:9200/index/fulltext/_search/
{
"query" : { "match" : { "content" : "中国嫌犯" }},
"highlight" : {
"pre_tags" : ["", ""],
"post_tags" : [" ", ""],
"fields" : {
"content" : {}
}
}
}