2015-05-20 199 views
0

下面顯示的是我的數據類型(表的種類)的結構。Elasticsearch DSL:聚合

Aircraft | Duration 
A320  | 0.95 
A320  | 0.55 
A321  | 16.50 
A321  | 3.9 

在這個數據,我想執行的時間一小區(),隨後是GROUPBY操作以獲取輸出如下:

Aircraft | Duration | Count 
A320  | 1  | 2 
A321  | 17  | 1 
A321  | 4  | 1 

回答

1

我自己基於對以下映射類型(編輯Duration作爲字符串):

curl -XPUT localhost:9200/tests -d ' 
{ 
    "mappings": { 
    "test1": { 
     "properties": { 
     "Aircraft": { 
      "type": "string" 
     }, 
     "Duration": { 
      "type": "string" 
     } 
     } 
    } 
    } 
}' 

並創建了四個與上面的數據表匹配的文檔。

curl -XPOST localhost:9200/tests/_bulk -d ' 
{"index": {"_type": "test1", "_id": 1}} 
{"Aircraft": "A320", "Duration": "0.95"} 
{"index": {"_type": "test1", "_id": 2}} 
{"Aircraft": "A320", "Duration": "0.55"} 
{"index": {"_type": "test1", "_id": 3}} 
{"Aircraft": "A321", "Duration": "16.50"} 
{"index": {"_type": "test1", "_id": 4}} 
{"Aircraft": "A321", "Duration": "3.9"} 
' 

聚集查詢將返回你所期望應該是這樣的結果:

curl -XPOST localhost:9200/tests/_search -d ' 
{ 
    "size": 0, 
    "query": { 
    "filtered": { 
     "filter": { 
     "terms": { 
      "Aircraft": [ 
      "a320", 
      "b737" 
      ] 
     } 
     } 
    } 
    }, 
    "aggs": { 
    "aircrafts": { 
     "terms": { 
     "field": "Aircraft" 
     }, 
     "aggs": { 
     "duration": { 
      "terms": { 
      "script": "Math.ceil(doc['Duration'].value as double)" 
      } 
     } 
     } 
    } 
    } 
}' 

該查詢的輸出是這樣的:

enter image description here

注意:請確保在您的elasticsearch.yml文件中啓用腳本,方法是加入

script.disable_dynamic: false 
+0

感謝您提供解決方案。我的'持續時間'實際上是字符串。我試過「script」:「Math.ceil(Double.parseDouble(doc ['Duration'] .value))」但沒有奏效。有什麼建議麼。 – Mohitt

+1

我編輯了我的答案並重新測試了OK。 – Val

+0

非常感謝。只是一個側面的問題。我有一個過濾條款來過濾一些特定的飛機。示例 - {\t 「條款」:{\t 「aircraft」:[「a320」,「b737」] }。在上面的查詢中應該插入哪裏? – Mohitt