【问题标题】:Elasticsearch leaderboard with player ranking带有玩家排名的 Elasticsearch 排行榜
【发布时间】:2020-06-15 16:07:00
【问题描述】:

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

我在 elastic 中存储以下数据:playerId、challengeId 和 score。

现在我想添加“位置”列(基于分数),但找不到在弹性中执行此操作的最有效方法。

用例:当我得到“challengeId 的所有玩家”时,我希望在响应中包含“位置”字段,其值基于“分数”值。

乍一看,文档提供了许多方法来做到这一点:聚合、评估 API、特征数据类型和特征数据类型。

有人在弹性中使用过这些东西吗?我可以选择其中一个来对排行榜中的玩家进行排名吗?

提前致谢。

【问题讨论】:

  • 我的回答好运吗?

标签: elasticsearch leaderboard


【解决方案1】:

您只需在score 字段上使用sort 即可实现它。为了更好地解释,我根据您的示例创建了一个包含一些示例数据的索引。更多关于排序功能的信息和示例可以在ES doc找到。

索引映射

{
    "mappings": {
        "properties": {
            "pid": {
                "type": "integer"
            },
            "cid" :{
                "type" : "integer"
            },
            "score" :{
                "type" : "integer"
            }
        }
    }
}

索引示例文档

  1. POST /_doc/1

    { “PID”:1, “cid”:1, “分数”:10 }

  2. 发布 /_doc/2

    { “PID”:2, “cid”:1, “分数”:9 }

  3. 发布 /_doc/3

    { “pid”:4, “cid”:1, “分数”:6 }

  4. POST /_doc/4

    { “pid”:4, “cid”:2, “分数”:10 }

  5. 发布 /_doc/5

    { “pid”:5, “cid”:2, “分数”:8 }

基于cid aka challengeID 获取记录并根据pid aka playeridscore 对结果进行排序的示例查询。

搜索查询

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

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    相关资源
    最近更新 更多