使用ElasticSearch聚合获取完整文档

时间:2015-12-10 15:22:37

标签: elasticsearch elasticsearch-aggregation

我有一个索引:

[
    {
        "Name": "Alex",
        "LastName": "Ich",
        "Department": 2
    },
    {
        "Name": "Charlie",
        "LastName": "Sheen",
        "Department": 3
    },
    {
        "Name": "Peter",
        "LastName": "Petrelli",
        "Department": 5
    },
    {
        "Name": "Alan",
        "LastName": "Harper",
        "Department": 6
    },
    {
        "Name": "Ann",
        "LastName": "Bottle",
        "Department": 3
    },
]

我希望得到不同Department的结果,我不关心顺序,每Department只有1个结果。我尝试使用聚合,但我只能通过关联 doc_count 来设法获得不同的Deppartments。他们查询我试过的是:

{
  "aggs": {
    "deppartments": {
      "terms": {
        "field": "Department"
      }
    }
  },"size": 0
}

它返回:

"buckets": [
    {
        "key": 2,
        "doc_count": 1
    },
    {
        "key": 3,
        "doc_count": 2
    },
    {
        "key": 5,
        "doc_count": 1
    },
    {
        "key": 6,
        "doc_count": 1
    },
]

当我想要这样的东西时:

[
    {
        "Name": "Alex",
        "LastName": "Ich",
        "Department": 2
    },
    {
        "Name": "Charlie",
        "LastName": "Sheen",
        "Department": 3
    },
    {
        "Name": "Peter",
        "LastName": "Petrelli",
        "Department": 5
    },
    {
        "Name": "Alan",
        "LastName": "Harper",
        "Department": 6
    }
]

1 个答案:

答案 0 :(得分:1)

您可以将Top hits aggregation用于此

{
  "aggs": {
    "departments": {
      "terms": {
        "field": "Department",
        "size": 10
      },
      "aggs": {
        "search_results": {
          "top_hits": {
            "size": 10   <--- you can change the size to 1 if you want
          }
        }
      }
    }
  },
  "size": 0
}

这有帮助吗?