按字段聚合,然后提取其他字段的最小值(如Group By& Having)

时间:2016-09-27 07:46:12

标签: elasticsearch

我在弹性数据库中有这个文档:

{
  ProcessInstanceId: aaaa-bbbb-cccc-dddd
  StartDateTime: 2016-09-27 08:00
  EndDateTime: 2016-09-27 08:01
}

{
  ProcessInstanceId: aaaa-bbbb-cccc-dddd
  StartDateTime: 2016-09-27 08:01
  EndDateTime: 2016-09-27 08:02
}


{
  ProcessInstanceId: aaaa-bbbb-cccc-dddd
  StartDateTime: 2016-09-27 08:02
  EndDateTime: 2016-09-27 08:03
}

{
  ProcessInstanceId: aaaa-bbbb-cccc-dddd
  StartDateTime: 2016-09-27 08:03
  EndDateTime: 2016-09-27 08:04
}

我的目标是获得输出:

{
  ProcessInstanceId: aaaa-bbbb-cccc-dddd
  MinStartDateTime: 2016-09-27 08:00
  MaxEndDateTime: 2016-09-27 08:04
}

这可能吗?

我试图使用聚合..但我不确定这是正确的方法:

GET /monitor*/_search
{
  "query": {
    "term": {
      "ProcessName": "SomeProcessName"
    }
  },
  "aggs": {
    "ProcessIDAgg": {
      "terms": {
        "field": "ProcessID.raw"
      },
      "aggs": {
        "MinAgg": {
          "min": {
            "field": "StartDateTime"
          }
        }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您走在正确的道路上,只需为max字段再添加一个EndDateTime指标聚合:

POST /monitor*/_search
{
  "query": {
    "term": {
      "ProcessName": "SomeProcessName"
    }
  },
  "aggs": {
    "ProcessIDAgg": {
      "terms": {
        "field": "ProcessID.raw"
      },
      "aggs": {
        "MinStartDateTime": {
          "min": {
            "field": "StartDateTime"
          }
        },
        "MaxEndDateTime": {
          "max": {
            "field": "EndDateTime"
          }
        }
      }
    }
  }
}