如何获得在相同键中具有最高_score的文档?

时间:2019-10-10 06:00:26

标签: elasticsearch

我正在研究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> }

1 个答案:

答案 0 :(得分:1)

您可以使用field collapsing并按_score排序

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