![](/img/trans.png)
[英]Elasticsearch: how to get the top unique values of a field sorted by matching score?
[英]How to get top 5 documents based on a stored field value in elasticsearch?
示例 - 學生的一個科目的考試成績存儲在彈性搜索索引中。 現在我想找到該科目得分最高的前 5 名學生。
讓我通過使用示例來展示它,但首先要了解這個概念。
根據給定的題目第一個查詢,在我的例子著名math
學科:),然后將獲取所有的學生,有math
學科,是經過sort
的desc
順序基於他們的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.