如何根据 elasticsearch 中存储的字段值获取前 5 个文档?

How to get top 5 documents based on a stored field value in elasticsearch?

示例 - 学生一门学科的考试成绩存储在 Elastic 搜索索引中。现在我想找到该科目得分最高的前 5 名学生。

只需按您想要的字段对搜索结果进行排序,即 score
该文档可能会对您有所帮助 https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-sort.html

让我用例子来说明,但首先要理解这个概念。

首先根据给定的主题进行查询,在我的示例中是著名的 math 主题 :) 然后它将获取所有具有 math 主题的学生,然后是 sort desc 基于 score 的顺序,然后 size 参数将结果限制为前 k 名学生。

与答案相关的 Imp 链接:

https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-from-size.html

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html

https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-sort.html

创建索引

{
    "mappings": {
        "properties": {
            "sid": {
                "type": "integer"
            },
            "subject" :{
                "type" : "keyword"
            },
            "score" :{
                "type" : "integer"
            }
        }
    }
}

索引一些文档

{
   "sid" : 1,
   "subject" :"math",
   "score" : 50
}

{
   "sid" : 2,
   "subject" :"math",
   "score" : 60
}
{
   "sid" : 3,
   "subject" :"math",
   "score" : 70
}
{
   "sid" : 4,
   "subject" :"math",
   "score" : 90
}
{
   "sid" : 5,
   "subject" :"math",
   "score" : 99
}

{
   "sid" : 6,
   "subject" :"math",
   "score" : 100
}

搜索查询 subject 并根据分数和 return 前 3 名学生对结果进行排序。

{
    "sort": [
        {
            "score": {
                "order": "desc" --> define sort order
            }
        }
    ],
    "query": {
        "term": {
            "subject": "math"
        }
    },
    "size":3 -->important, you can change it to fetch top K students, Just change 3 to whatever no you want to fetch.
}

搜索查询结果

{
            "_index": "leaderboard",
            "_type": "_doc",
            "_id": "5",
            "_score": null,
            "_source": {
               "sid": 6,
               "subject": "math",
               "score": 100
            },
            "sort": [
               100
            ]
         },
         {
            "_index": "leaderboard",
            "_type": "_doc",
            "_id": "4",
            "_score": null,
            "_source": {
               "sid": 4,
               "subject": "math",
               "score": 90
            },
            "sort": [
               90
            ]
         },
         {
            "_index": "leaderboard",
            "_type": "_doc",
            "_id": "3",
            "_score": null,
            "_source": {
               "sid": 3,
               "subject": "math",
               "score": 70
            },
            "sort": [
               70
            ]
         }