簡體   English   中英

如何根據elasticsearch中存儲的字段值獲取前5個文檔?

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

示例 - 學生的一個科目的考試成績存儲在彈性搜索索引中。 現在我想找到該科目得分最高的前 5 名學生。

讓我通過使用示例來展示它,但首先要了解這個概念。

根據給定的題目第一個查詢,在我的例子著名math學科:),然后將獲取所有的學生,有math學科,是經過sortdesc順序基於他們的score ,然后size PARAM限制的結果頂部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並根據分數對結果進行排序並返回前 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
            ]
         }

只需按您想要的字段對搜索結果進行排序,即score
該文檔可以幫助您https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-sort.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM