2016-08-24 65 views
2

我在Elasticsearch中处理的文档代表警报。这些警报会被激活一段时间,并且看起来像下一个文档。ElasticSearch日期直方图聚合考虑文档范围内的日期

{ 
    "id": 189393, 
    "sensorId": "1111111", 
    "activationTime": 1462569310000, 
    "deactivationTime": 1462785524876, 
} 

我想知道一天当中的活动警报的数量。为此,我希望执行日期直方图聚合,以考虑警报处于活动状态的日期,因为当我执行简单日期直方图聚合时,警报仅被视为活动时间。

例如,我想知道哪些日子已被激活前一次警报,并执行此查询。

{ 
    "query" : { 
     ... 
    }, 
    "aggs": { 
    "active_alerts": { 
     "date_histogram": { 
     "field": "timestamp", 
     "interval": "day" 
     } 
    } 
    } 
} 

返回

"aggregations": { 
    "active_alerts": { 
     "buckets": [ 
      { 
       "key_as_string": "2016-05-06T00:00:00.000Z", 
       "key": 1462492800000, 
       "doc_count": 1 
      } 
     ] 
    } 
} 

这我想回

"aggregations": { 
    "active_alerts": { 
     "buckets": [ 
      { 
       "key_as_string": "2016-05-06T00:00:00.000Z", 
       "key": 1462492800000, 
       "doc_count": 1 
      }, 
      { 
       "key_as_string": "2016-05-07T00:00:00.000Z", 
       "key": 1462579200000, 
       "doc_count": 1 
      }, 
      { 
       "key_as_string": "2016-05-08T00:00:00.000Z", 
       "key": 1462665600000, 
       "doc_count": 1 
      } 
     ] 
    } 
} 

感谢。

回答

1

最后我发现通过脚本的解决方案,创建一个发射从激活日期到停用日期的一系列日期。

"aggs": { 
    "active_alerts": { 
     "date_histogram": { 
     "interval": "day", 
     "script": "Date d1 = new Date(doc['activationTime'].value); Date d2 = new Date(doc['deactivationTime'].value); List<Date> dates = new ArrayList<Date>(); (d1..d2).each { date-> dates.add(date.toTimestamp().getTime())}; return dates;" 
     } 
    } 
    } 

谢谢。

2

我想你来自哪里,该时间间隔添加“丢失”的日子里,你有你编程只能照本宣科dateHistogram做到这一点:

"aggs": { 
    "active_alerts": { 
     "date_histogram": { 
     "interval": "day", 
     "script": "counter=0;combinedDates=[];currentDate=doc.activationTime.date;while(currentDate.isBefore(doc.deactivationTime.date.getMillis())){combinedDates[counter++]=currentDate.getMillis();currentDate.addDays(1)};combinedDates[counter]=doc.deactivationTime.date.getMillis();return combinedDates" 
     } 
    } 
    } 
+0

昨天我找到了解决方案,但我无法写出答案。谢谢你:) – Sapikelio

+1

是的,这几乎是基本的想法。您也可以在索引时间执行此操作,并通过在单个“日期”字段中将所有日期(天)编入索引来节省一些搜索时间。 –