2016-04-24 205 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版本。 –