场景需求
一个模型多个字段,给每个字段的匹配都设定相应的分值,总和大于某个分值则认为匹配成功
官网地址
https://www.elastic.co/guide/en/elasticsearch/reference/8.1/query-dsl-function-score-query.html
实现方案
# 索引设置
PUT /test_index
{
"settings": {
"index": {
"analysis": {
"analyzer": {
"my_ik": {
"type": "custom",
"tokenizer": "ik_smart",
"filter": [
"my_synonym"
]
}
},
"filter": {
"my_synonym": {
"type": "synonym_graph",
"synonyms_path": "analysis/synonym.txt"
}
}
}
}
},
"mappings": {
"properties": {
"key1": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"analyzer": "my_ik"
},
"key2": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"analyzer": "my_ik"
},
"key3": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"analyzer": "my_ik"
},
"key4": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
},
"analyzer": "my_ik"
},
"context": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
}
}
# 数据插入
POST _bulk
{"index":{"_index":"test_index","_id":1}}
{"key1":"1","key2":"11","key3":"111","key4":"1111"}
{"index":{"_index":"test_index","_id":2}}
{"key1":"2","key2":"22","key3":"2222","key4":"2222"}
{"index":{"_index":"test_index","_id":3}}
{"key1":"3","key2":"33","key3":"333","key4":"3333"}
{"index":{"_index":"test_index","_id":4}}
{"key1":"4","key2":"44","key3":"444","key4":"4444","context":"张老师"}
# 查询
GET test_index/_search
{
"query": {
"function_score": {
"query": {
"bool": {
"should": [
{
"terms": {
"key1": [
"1"
]
}
},
{
"terms": {
"key3": [
"red"
]
}
}
]
}
},
"functions": [
{
"filter": {
"terms": {
"key1": [
"1"
]
}
},
"weight": 1
},
{
"filter": {
"term": {
"key2": "22"
}
},
"weight": 2
}
],
"max_boost": 100,
"score_mode": "sum",
"boost_mode": "replace",
"min_score": 1
}
}
}