我想将以下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"
}
}
}
}
}
}
但不确定我是否正确,因为它没有验证结果。 似乎要在聚合内添加查询。
答案 0 :(得分: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的条款,则不会产生任何结果。