2016-04-24 206 views
3

我想將以下sql查詢轉換爲Elasticsearch。任何人都可以幫忙。將SQL查詢轉換爲ElasticSearch查詢

select csgg, sum(amount) from table1 
where type in ('a','b','c') and year=2016 and fc="33" group by csgg having sum(amount)=0 

我嘗試以下方法:enter code here

{ 
    "size": 500, 
    "query" : { 
     "constant_score" : { 
     "filter" : { 
      "bool" : { 
       "must" : [ 
       {"term" : {"fc" : "33"}}, 
       {"term" : {"year" : 2016}} 
       ], 
       "should" : [ 
       {"terms" : {"type" : ["a","b","c"] }} 
       ] 
      } 
     } 
     } 
    }, 
    "aggs": { 
    "group_by_csgg": { 
     "terms": { 
     "field": "csgg" 
     }, 
     "aggs": { 
     "sum_amount": { 
      "sum": { 
      "field": "amount" 
      } 
     } 
     } 
    } 
    } 
} 

,但不知道我在做正確的爲沒有驗證的結果。 似乎查詢被添加到聚合內。

回答

2

假設您使用Elasticsearch 2.x,Elasticsearch中有可能使具有的語義。 我不知道2.0之前的可能性。

您可以使用新的管道匯聚Bucket Selector Aggregation,只選擇水桶,其中符合一定條件的:

POST test/test/_search 
{ 
    "size": 0, 
    "query" : { 
     "constant_score" : { 
     "filter" : { 
      "bool" : { 
       "must" : [ 
       {"term" : {"fc" : "33"}}, 
       {"term" : {"year" : 2016}}, 
       {"terms" : {"type" : ["a","b","c"] }} 
       ] 
      } 
     } 
     } 
    }, 
    "aggs": { 
    "group_by_csgg": { 
     "terms": { 
     "field": "csgg", 
     "size": 100 
     }, 
     "aggs": { 
     "sum_amount": { 
      "sum": { 
      "field": "amount" 
      } 
     }, 
     "no_amount_filter": { 
      "bucket_selector": { 
      "buckets_path": {"sumAmount": "sum_amount"}, 
      "script": "sumAmount == 0" 
      } 
     } 
     } 
    } 
    } 
} 

然而,有兩點需要說明。根據您的配置,這可能需要enable scripting這樣的:

script.aggs: true 
script.groovy: true 

而且,因爲它適用於= 0。如果條件聚合只選擇它不能保證你得到所有水桶量父桶總金額!= 0的條款,你將沒有結果。

+0

需要採取的行動如下: script.aggs:true script.groovy:true它也像下面這樣說:解析失敗[在[no_amount_filter]]中找不到聚合器類型[bucket_selector]]]; }] – fasterslow2007

+1

你使用Elasticsearch版本> = 2.0.0嗎?對我來說,這聽起來像你使用的是1.x版本。 –