安装分词工具IK Analysis
IK Analysis 插件(https://github.com/medcl/elasticsearch-analysis-ik/)就是一款专门用于 Elasticsearch 的分词器,可以友好的处理中文。
github地址:https://github.com/medcl/elasticsearch-analysis-ik/releases
在安装完elasticsearch后,(如果没有安装elasticsearch,附上连接:https://blog.csdn.net/qq_24265945/article/details/81015048)
打开命令行,转到安装elasticsearch路径:
随后 输入命令:
elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.2.4/elasticsearch-analysis-ik-6.2.4.zip
注意这里的6.2.4是我的elasticsearch版本,你只需要改成你安装的elasticsearch的版本就可以
使用 IK:
1.在可视化界面kibana输入:PUT /index 创建索引index
2.创建mapping:
POST /index/fulltext/_mapping
{
"properties": {
"content": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}
3.输入例子
curl -XPOST http://localhost:9200/index/fulltext/1 -H 'Content-Type:application/json' -d'
{"content":"美国留给伊拉克的是个烂摊子吗"}
'
curl -XPOST http://localhost:9200/index/fulltext/2 -H 'Content-Type:application/json' -d'
{"content":"公安部:各地校车将享最高路权"}
'
curl -XPOST http://localhost:9200/index/fulltext/3 -H 'Content-Type:application/json' -d'
{"content":"中韩渔警冲突调查:韩警平均每天扣1艘中国渔船"}
'
curl -XPOST http://localhost:9200/index/fulltext/4 -H 'Content-Type:application/json' -d'
{"content":"中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"}
'
4.输入查询:
curl -XPOST http://localhost:9200/index/fulltext/_search -H 'Content-Type:application/json' -d'
{
"query" : { "match" : { "content" : "中国" }},
"highlight" : {
"pre_tags" : ["<tag1>", "<tag2>"],
"post_tags" : ["</tag1>", "</tag2>"],
"fields" : {
"content" : {}
}
}
}
'
运行结果:
这里有一个问题:https://stackoverflow.com/questions/37628981/mapper-for-conflicts-with-existing-mapping
在你数据已经插入的情况下是没有办法改变es自己创建的默认映射mapping,只能在插入数据前写好mapping或者在默认设置里关闭es的自动创建映射。否则,会像我一样报错:
{
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Mapper for [summary] conflicts with existing mapping in other types:\n[mapper [summary] has different [analyzer]]"
}
],
"type": "illegal_argument_exception",
"reason": "Mapper for [summary] conflicts with existing mapping in other types:\n[mapper [summary] has different [analyzer]]"
},
"status": 400
}
解决方法:我决定先设置mapping做中文分词 ,再把数据重新导入一遍