1、创建索引时指定同义词
- 下载elasticsearch-7.10.0版本,并解压:https://www.elastic.co/cn/downloads/past-releases/elasticsearch-7-10-0
- 下载IK分词器7.10.0版本,并解压到指定文件夹下(elasticsearch-7.10.0/plugins/),文件夹改名为ik:https://github.com/medcl/elasticsearch-analysis-ik/releases/tag/v7.10.0
- 运行ES,cd到elasticsearch-7.10.0/bin/目录下,执行“./elasticsearch”,可以看到运行时,成功加载了ik分词器插件
- 运行es-head插件,进入可视化页面,执行创建索引操作,并指定同义词配置
PUT http://localhost:9200/test01_index
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0,
"index": {
"analysis": {
"filter": {
"doc_synonym": {
"type": "synonym",
"synonyms": [
"双十一,双11=>购物节",
"中秋,月饼=>中秋节",
"iphone,苹果手机,iphone13Pro",
"小米,小米手机",
"小米,小米电脑"
]
}
},
"analyzer": {
"my_doc_syno": {
"type": "custom",
"tokenizer": "ik_smart",
"filter": [
"doc_synonym"
]
}
}
}
}
},
"mappings": {
"properties": {
"name": {
"type": "text",
"analyzer": "my_doc_syno"
},
"remark": {
"type": "text",
"analyzer": "my_doc_syno"
}
}
}
}
- 创建完成,可看到正确返回
- 此时,可通过head插件查看到索引属性
- 接下来我们进入到验证环节,看是否同义词设置成功
POST http://localhost:9200/test01_index/_analyze/
{
"field": "name",
"text": "双十一,iphone,小米"
}
- 其实到这里,已经能证实同义词设置成功了。我们进一步证实下,先尝试下插入两条模拟数据,进行验证
POST http://localhost:9200/test01_index/_doc/
{
"name": "张三",
"remark": "因为爱玩手机,所以小名叫iphone"
}
POST http://localhost:9200/test01_index/_doc/
{
"name": "李四",
"remark": "因为出生时是11月11日,所以热爱购物"
}
- 尝试搜索关键字“苹果”,经过同义词转换,可实现对“iphone,苹果手机,iphone13Pro”三个词的同义转换,再进行搜索
POST http://localhost:9200/test01_index/_search/
{
"query": {
"query_string": {
"fields": [
"name",
"remark"
],
"query": "苹果"
}
}
}
- 尝试搜索关键字“双十一”,经过同义词转换,可实现对“购物、节”两个词的同义转换,再进行搜索
POST http://localhost:9200/test01_index/_search/
{
"query": {
"query_string": {
"fields": [
"name",
"remark"
],
"query": "双十一"
}
}
}