[英]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.