获取ElasticSearch中的最新记录

时间:2016-11-02 14:15:22

标签: elasticsearch

我有以下表结构

change_id    saveDate     id
-------------------------------
1            2014-04-01  205
2            2014-05-01  205
3            2014-03-31  111
4            2014-04-01  111
5            2014-04-01  333

现在我想得到特定ids = [205,111]的最新记录。 我应该用change_id [2,4]来获取记录。

我的ElasticSearch查询到目前为止:

    {
        "fields": [
            "Something.id",
            "Something.change_id",
            "Something.saveDate"
        ],
        "query": {
            "terms": {
                "Something.id": [
                    "2015",
                    "111"
                ]
            }
        },
        "sort": [
            {
                "Something.saveDate": {
                    "order": "desc"
                }
            }
        ],
        "aggs": {
            "id": {
                "terms": {
                    "field": "Something.id",
                    "size": 20
                }
            }
        }
    }

我得到4行的结果change_id = [2,1,4,3],它按照saveDate对desc进行排序。

如何使用查询过滤它并获取两行,其中change_id = [4,2]?

1 个答案:

答案 0 :(得分:2)

您可以使用top_hits aggregation来实现此目的。它还具有source filtering和排序功能。

{
  "query": {
    "bool": {
      "filter": {
        "terms": {
          "Something.id": [
            "205",
            "111"
          ]
        }
      }
    }
  },
  "size": 0,
  "aggs": {
    "unique_id": {
      "terms": {
        "field": "Something.id",
        "size": 20
      },
      "aggs": {
        "top_result": {
          "top_hits": {
            "size": 1,
            "_source": ["Something.id", "Something.change_id", "Something.saveDate"],
            "sort": {
              "Something.saveDate" : "desc"
            }
          }
        }
      }
    }
  }
}