【发布时间】:2020-06-16 18:59:58
【问题描述】:
示例 - 一门学生的考试成绩存储在 Elastic 搜索索引中。现在我想找出该科目得分最高的前 5 名学生。
【问题讨论】:
-
@S Khandelwal,感谢您接受我的回答并很高兴它很有用,您也可以通过单击我的回答前面的向上箭头来支持我的回答 :-)
标签: sorting elasticsearch filter elasticsearch-aggregation
示例 - 一门学生的考试成绩存储在 Elastic 搜索索引中。现在我想找出该科目得分最高的前 5 名学生。
【问题讨论】:
标签: sorting elasticsearch filter elasticsearch-aggregation
让我用例子来展示一下,但首先要理解这个概念。
基于给定主题的第一个查询,在我的示例中是著名的math 主题:) 然后它将获取所有具有math 主题的学生,然后是desc 中的sort,基于他们的@ 顺序987654328@ 然后size 参数将结果限制为顶部k 学生。
与答案相关的展示链接:
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
【讨论】: