我正在尝试找到最佳的解决方案以通过Elasticsearch实施排行榜。
我以弹性方式存储以下数据:playerId,challengeId和得分。
现在,我想添加“位置”列(基于得分),但找不到哪种方法可以最有效地做到这一点。
用例:当我通过“挑战ID”获得“所有玩家”时,我希望响应中的“位置”字段的值基于“得分”值。
乍看之下,文档提供了许多方法来执行此操作:聚合,评估API,要素数据类型和要素数据类型。
有人使用过弹性的东西吗?我可以选择其中一种在排行榜中排名玩家吗?
提前感谢。
您可以通过在sort
字段上使用score
来简单地实现它。为了更好的解释,我根据您的示例创建了一个包含一些示例数据的索引。可以在ES doc中找到有关排序功能的更多信息以及示例。
{
"mappings": {
"properties": {
"pid": {
"type": "integer"
},
"cid" :{
"type" : "integer"
},
"score" :{
"type" : "integer"
}
}
}
}
POST / _doc / 1
{“ pid”:1“ cid”:1,“得分”:10}
POST / _doc / 2
{“ pid”:2“ cid”:1,“得分”:9}
POST / _doc / 3
{“ pid”:4“ cid”:1,“得分”:6}
POST / _doc / 4
{“ pid”:4“ cid”:2,“得分”:10}
POST / _doc / 5
{“ pid”:5“ cid”:2,“得分”:8}
根据cid
aka challengeID
提取记录并根据score
aka pid
的playerid
排序结果的样本查询。
{
"sort": [
{
"score": {
"order": "desc" --> notice `desc` order on `score` field
}
}
],
"query": {
"term": {
"cid": 2
}
}
}
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": null,
"hits": [
{
"_index": "leaderboard",
"_type": "_doc",
"_id": "4",
"_score": null,
"_source": {
"pid": 4,
"cid": 2,
"score": 10
},
"sort": [
10
]
},
{
"_index": "leaderboard",
"_type": "_doc",
"_id": "5",
"_score": null,
"_source": {
"pid": 5,
"cid": 2,
"score": 8
},
"sort": [
8
]
}
]
}
[注意,搜索查询返回了2个文档,它们的cid
= 2,并且玩家ID按照其score
的降序排列。