2014-09-26 18 views
5

我需要做的得到按周和小時的天分組的一些數據的天團,例如Elasticsearch - 按周和小時

curl -XGET http://localhost:9200/testing/hello/_search?pretty=true -d ' 
{ 
     "size": 0, 
     "aggs": { 
      "articles_over_time" : { 
      "date_histogram" : { 
       "field" : "date", 
       "interval" : "hour", 
       "format": "E - k" 
      } 
      } 
     } 
} 
' 

給了我這樣的:

{ 
    "took" : 2, 
    "timed_out" : false, 
    "_shards" : { 
    "total" : 5, 
    "successful" : 5, 
    "failed" : 0 
    }, 
    "hits" : { 
    "total" : 2857, 
    "max_score" : 0.0, 
    "hits" : [ ] 
    }, 
    "aggregations" : { 
    "articles_over_time" : { 
     "buckets" : [ { 
     "key_as_string" : "Fri - 17", 
     "key" : 1391792400000, 
     "doc_count" : 6 
     }, 
    ... 
     { 
     "key_as_string" : "Wed - 22", 
     "key" : 1411596000000, 
     "doc_count" : 1 
     }, { 
     "key_as_string" : "Wed - 22", 
     "key" : 1411632000000, 
     "doc_count" : 1 
     } ] 
    } 
    } 
} 

現在我需要通過這個值「星期二 - 22」來總結文檔計數,我該怎麼做? 也許還有一些方法?

回答

0

您可以嘗試使用子聚合從聚合結果中對「key_as_string」字段進行術語聚合。

希望有所幫助。

1

this thread已解決同樣的問題。

適應的解決您的問題,我們需要一個腳本將日期轉換爲星期幾和一天的小時:

Date date = new Date(doc['date'].value) ; 
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat('EEE, HH'); 
format.format(date) 

而且在查詢中使用它:

{ 
    "aggs": { 
     "perWeekDay": { 
      "terms": { 
       "script": "Date date = new Date(doc['date'].value) ;java.text.SimpleDateFormat format = new java.text.SimpleDateFormat('EEE, HH');format.format(date)" 
      } 
     } 
    } 
} 
0

這是因爲您使用的時間間隔爲'小時',但日期格式爲'日'(E - k)。

將您的間隔更改爲'日',並且您將不再爲'Weds - 22'獲取單獨的桶。或者,如果您每小時都想要,那麼請將您的格式更改爲包含小時字段。

+0

非腳本解決方案的一個缺點是,如果查詢跨越多個日期,您每小時可以獲得多個值,但我當前的解決方案是將其與客戶端結合使用,因爲我希望避免必須打開腳本爲了這。 – centic 2016-04-27 12:20:52

+0

不知道我按照你的評論:-)。間隔和格式有關 - 間隔控制桶,格式控制桶的名稱。如果您希望存儲桶名稱都是唯一的,則必須適當地設置格式。 ?!或者,忽略'key_as_string'並使用'key'代替;-)。 – RichS 2016-04-27 14:29:21

+0

我的目標是獲得更長時間的「每日小時」歷史紀錄。它應該顯示凌晨1點,凌晨2點,凌晨3點發生了多少事情。現在,如果我設置時間間隔:「小時」和格式:「HH」,我會得到預期的小時桶key_as_string「01」,「02」,...,但每天都會重複,因此我得到多個「01 「以及多個」02「,... – centic 2016-04-27 18:50:13