一、题目
索引 movie,保存的电影信息,title是题目,tags是电影的标签。
要求:
在title中包含“my” 或者 “me”。
如果在tags中包含 "hot",该条算分提高,如果不包含则算分不变
二、思考
1)要求1说对title字段查,要求包含my 或 me,我们首先应该想到bool中的should。但是这里有一点要注意,bool中如果只有一个should,没有使用must或filter需要指定 “minimum_should_match=1”,也就是说至少要匹配一个。
2)要求如果tags中包含 “hot”,则提高分数,这里应该想到function score
三、解题
Step 1、准备索引和测试数据
# DELETE movie
PUT movie
{
"mappings": {
"properties": {
"title":{
"type": "text"
},
"tags":{
"type": "keyword"
}
}
}
}
PUT movie/_bulk
{"create":{"_id":1}}
{"title":"my sun", "tags":["top","hot"]}
{"create":{"_id":2}}
{"title":"hello world", "tags":["normal"]}
{"create":{"_id":3}}
{"title":"Apple", "tags":["normal"]}
Step 2、定义 function score 查询
注意:
1)bool中should 中参数 minimum_should_match
2)function_score中可以通过functions,script_score,random_score 三种方式自定义评分
3)function_score中 functions 注意有s,也就是代表是多个,是数组方式,通过指定 weight值来增加查询评分
GET movie/_search
{
"query": {
"function_score": {
"query": {
"bool": {
"should": [
{
"match": {
"title": "my"
}
},
{
"match": {
"title": "me"
}
}
],
"minimum_should_match": 1
}
},
"functions": [
{
"filter": {
"match": {
"tags": "hot"
}
},
"weight": 10
}
]
}
}
}
四、总结
1)function_score中标准模版用法
GET /_search
{
"query": {
"function_score": {
"query": {
"match_all": {}
},
"boost": "5",
"functions": [
{
"filter": {},
"weight": 2
}
],
"random_score": {},
"boost_mode": "multiply"
}
}
}
2) bool中should 中参数 minimum_should_match
参考资料
- Function score query | Elasticsearch Guide [8.1] | Elastic
- Boolean query | Elasticsearch Guide [8.1] | Elastic
送一波福利:
福利一
有需要内推JD的同学,可以私信或留言,我帮您内推,流程快!!!
有需要内推JD的同学,可以私信或留言,我帮您内推,流程快!!!
有需要内推JD的同学,可以私信或留言,我帮您内推,流程快!!!
福利二
福利三