Created
September 8, 2015 06:28
-
-
Save kakakazuma/c8efe27f1d07c99c5af6 to your computer and use it in GitHub Desktop.
elasticsearch aggregation sample by java. double group by.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
ES Aggregation to get result same as result from this SQL | |
SELECT | |
fieldA, fieldC, SUM(fieldB) | |
from table | |
group by fieldA,fieldC; | |
*/ | |
SearchRequestBuilder searchReq = client.prepareSearch("sample_index"); | |
searchReq.setTypes("sample_types"); | |
TermsBuilder termsb_fa = AggregationBuilders.terms("my_fieldA").field("fieldA").size(100); | |
TermsBuilder termsb_fc = AggregationBuilders.terms("my_fieldC").field("fieldC").size(50); | |
termsb_fc.subAggregation(AggregationBuilders.sum("my_sum_fieldB").field("fieldB")); | |
termsb_fa.subAggregation(termsb_fc) | |
searchReq.setQuery(QueryBuilders.matchAllQuery()).addAggregation(termsb_fa); | |
SearchResponse searchRes = searchReq.execute().actionGet(); | |
Terms fieldATerms = searchRes.getAggregations().get("my_fieldA"); | |
for (Terms.Bucket filedABucket : fieldATerms.getBuckets()) { | |
//fieldA | |
String fieldAValue = filedABucket.getKey(); | |
Terms fieldCTerms = filedABucket.getAggregations().get("my_fieldC"); | |
for (Terms.Bucket filedCBucket : fieldCTerms.getBuckets()) { | |
//fieldC | |
String fieldCValue = filedCBucket.getKey(); | |
//SUM(fieldB) | |
Sum sumagg = filedCBucket.getAggregations().get("my_sum_fieldB"); | |
long sumFieldB = (long)sumagg.getValues(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment