1. 创建索引 test setting和mappings
设置了自定义分词映射规则。
PUT /test
{
"settings": {
"analysis": {
"filter": {
"my_synonym": {
"type": "synonym",
"updateable": true,
"synonyms_path": "dic/synonyms.txt"
}
},
"analyzer": {
"my_analyzer": {
"tokenizer": "ik_max_word",
"filter": [
"my_synonym"
]
}
}
}
},
"mappings": {
"properties": {
"name": {
"type": "text",
"analyzer": "ik_max_word"
}
}
}
}
dic/synonyms.txt文件中的映射词如下:
张三,李四 => 王五
电脑 => 计算机
苹果 => 苹果电脑
2. 向test索引中写入数据
PUT test/_doc/1
{
"name":"电脑"
}
PUT test/_doc/2
{
"name":"苹果"
}
PUT test/_doc/3
{
"name":"王五"
}
3. 查询
使用bool查询数据。
#查询语句
GET test/_search/
{
"query": {
"bool": {
"must": [
{
"match":{
"name":{
"query":"张三,李四",
"analyzer":"my_analyzer"
}
}
}
]
}
}
}
#查询结果
{
"took" : 831,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 3.257093,
"hits" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "3",
"_score" : 3.257093,
"_source" : {
"name" : "王五"
}
}
]
}
}
以上查询中query中指定查询“张三,李四”,同时由于指定了自定义分词映射规则,会自动将“张三,李四”映射为“王五”进行查询,结果所以会查询出“王五”。