首页 > 解决方案 > 如何获取相同键中具有最高 _score 的文档?

问题描述

我正在研究 Elasticsearch。如何获取相同键中具有最高 _score 的文档?我应该使用或阅读哪个 API?

示例文档和查询

{ "foreignId": 1, "body": "One is a green apple, however another one is red."}
{ "foreignId": 1, "body": "apple apple apple apple" } // has a higher score than the one right above
{ "foreignId": 2, "body": "One is a green apple, however another one is red."}
{ "foreignId": 2, "body": "apple apple apple" } // has a higher score than the one right above

{"query": { "match_phrase": { "body": "apple"}}}

预期的

{ "foreignId": 1, "body": "apple apple apple apple", _score: <the highest where foreignId=1> }
{ "foreignId": 2, "body": "apple apple apple", _score: <the highest where foreignId=2> }

标签: elasticsearch

解决方案


您可以使用字段折叠并按 _score 排序

{
  "query": {
    "match_phrase": {
      "body": "apple"
    }
  },
  "collapse": {
    "field": "foreignId"
  },
  "sort": ["_score"]
}

推荐阅读