具有玩家排名的Elasticsearch排行榜

问题描述 投票:0回答:1

我正在尝试找到最佳的解决方案以通过Elasticsearch实施排行榜。

我以弹性方式存储以下数据:playerId,challengeId和得分。

现在,我想添加“位置”列(基于得分),但找不到哪种方法可以最有效地做到这一点。

用例:当我通过“挑战ID”获得“所有玩家”时,我希望响应中的“位置”字段的值基于“得分”值。

乍看之下,文档提供了许多方法来执行此操作:聚合,评估API,要素数据类型和要素数据类型。

有人使用过弹性的东西吗?我可以选择其中一种在排行榜中排名玩家吗?

提前感谢。

elasticsearch leaderboard
1个回答
0
投票

您可以通过在sort字段上使用score来简单地实现它。为了更好的解释,我根据您的示例创建了一个包含一些示例数据的索引。可以在ES doc中找到有关排序功能的更多信息以及示例。

索引映射
{
    "mappings": {
        "properties": {
            "pid": {
                "type": "integer"
            },
            "cid" :{
                "type" : "integer"
            },
            "score" :{
                "type" : "integer"
            }
        }
    }
}

索引样本文档
  1. 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 pidplayerid排序结果的样本查询。

    搜索查询
    {
        "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的降序排列。

    © www.soinside.com 2019 - 2024. All rights reserved.