先ElasticSearch排序再聚合将导致排序失败

mum43rcc  于 2023-05-06  发布在  ElasticSearch
关注(0)|答案(1)|浏览(93)

我是elasticsearch的初学者,想实现一个函数,有一个es_game保存所有游戏的信息,我需要按时间倒序查询所有游戏的数据,但是如果game_id相同,只会返回一个新的,下面是我的dsl方法,但是返回的数据不是最新的看来先排序再聚合会导致排序失败我想按时间倒序查询最新数据,谢谢。
这是我的错误DSL

{
  "size": 0,
  "query": {
      "filter": [
        {
          "range": {
            "create_time": {
              "gte": "2023-05-01 11:56:45",
              "lte": "2023-05-31 11:56:45"
            }
          }
        }
      ]
  },

  "sort": [
    {
      "create_time": {
        "order": "desc"
      }
    }
  ],

  "aggs": {
    "group_by_game": {
      "terms": {
        "field": "game_id"
      },
    
      "aggs": {
        "sort_by_create_time": {
          "top_hits": {
            "sort": [
              {
                "create_time": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  }
}
class Game {
    private Integer gameId;
    private String createTime;
...
}

你能引导我修改ElasticSearchdsl吗

nwo49xxi

nwo49xxi1#

我测试了你的场景,它看起来很好。我错过什么了吗?

PUT test_game
{
  "mappings": {
    "properties": {
      "create_time": {
        "type": "date",
        "format": ["yyyy-MM-DD HH:mm:ss"]
      }
    }
  }
}

POST test_game/_bulk
{ "create":{ } }
{ "create_time": "2099-05-06 16:21:15", "game_id": 1 }
{ "create":{ } }
{ "create_time": "2079-05-06 16:21:15", "game_id": 2 }
{ "create":{ } }
{ "create_time": "2085-05-06 16:21:15", "game_id": 1 }

GET test_game/_search
{
  "size": 0,
  "query": {
    "range": {
      "create_time": {
        "gte": "2023-05-01 11:56:45",
        "lte": "2100-01-31 11:56:45"
      }
    }
  },
  "sort": [
    {
      "create_time": {
        "order": "desc"
      }
    }
  ],
  "aggs": {
    "group_by_game": {
      "terms": {
        "field": "game_id"
      },
      "aggs": {
        "sort_by_create_time": {
          "top_hits": {
            "sort": [
              {
                "create_time": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  }
}

相关问题