2016-08-24 78 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

是的,這幾乎是基本的想法。您也可以在索引時間執行此操作,並通過在單個「日期」字段中將所有日期(天)編入索引來節省一些搜索時間。 –