我有以下搜索查询,该查询返回包含单词“apple”、“mango”或“strawberry”的文档。现在,每当文档中出现“蛋糕”或“薯条”(或两者)一词时,我想提高文档的评分(蛋糕或薯条一词不必出现在文档中,但每当它出现在“标题”中时,我想提高文档的评分"或 "body"字段,应提高评分,以便包含 "cake"或 "chips"的文档排名更高)
res = es.search(index='fruits', body={
"query": {
"bool": {
"must": [
{
"query_string": {
"query": "(apple) OR (mango) OR (strawberry)"
}
},
{
"bool": {
"must_not": [{
"match_phrase": {
"body": "Don't match this phrase."
}
}
]
}
}
]
},
"match": {
"query": "(cake) OR (chips)",
"boost": 2
}
}
}
})
任何帮助将不胜感激!
最佳答案
只需在 should 中包含您想要提升的值即可子句如以下查询所示:
查询:
POST <your_index_name>/_search
{
"query":{
"bool":{
"must":[
{
"query_string":{
"query":"(apple) OR (mango) OR (strawberry)"
}
},
{
"bool":{
"must_not":[
{
"match_phrase":{
"body":"Don't match this phrase."
}
}
]
}
}
],
"should":[ <----- Add this
{
"query_string":{
"query":"cake OR chips",
"fields": ["title","body"], <----- Specify fields
"boost":10 <----- Boost Field
}
}
]
}
}
}
或者,您可以推送 must_not子句到查询中的上一级。
更新的查询:
POST <your_index_name>/_search
{
"query":{
"bool":{
"must":[
{
"query_string":{
"query":"(apple) OR (mango) OR (strawberry)"
}
}
],
"should":[
{
"query_string":{
"query":"cake OR chips",
"fields": ["title","body"],
"boost":10
}
}
],
"must_not":[ <----- Note this
{
"match_phrase":{
"body":"Don't match this phrase."
}
}
]
}
}
}
基本上,should
限定为逻辑 OR,而 must
则用作逻辑 AND 就 bool 运算而言。
通过这种方式,查询将提高结果或文档的顺序,因为它将具有更高的相关性分数,而那些仅符合仅在必须条件下的结果或文档将具有较低的相关性。
希望这有帮助!
关于python - Elasticsearch - 如果单个术语出现在字段中,则提升该术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58870386/