I want to implement this json query using ES java client:
{
"query": {
"bool": {
"must_not": [
{
"terms": {
"is_reversed": [
1,
2
]
}
}
],
}
},
"aggs": {
"my_buckets": {
"composite": {
"sources": [
{
"myfield_id": {
"terms": {
"field": "myfield_id",
"missing_bucket": true
}
}
}
],
"size": 65535
},
"aggregations": {
"sum": {
"sum": {
"field": "amount"
}
}
}
}
}
}
I use new elasticsearch-java v8.2 api. it has a few documentation and example.
here's my code:
Query byReveredTransactionType = TermQuery.of(t ->
t.field("is_reversed")
.value(1))._toQuery();
Map<String, CompositeAggregationSource> sources = Map.of("category_id", CompositeAggregationSource.of(b -> b
.terms(t -> t.field("category_id")
.missingBucket(true))));
SearchRequest req = SearchRequest.of(r -> r
.query(q -> q
.bool(b -> b.mustNot(byReveredTransactionType))
)
.aggregations("my_buckets", AggregationBuilders.composite().sources(sources).build()._toAggregation())
.size(Short.MAX_VALUE * 2 - 1)
.build()._toAggregation()
);
here's the code json output:
{
"aggregations": {
"my_buckets": {
"composite": {
"sources": [
{
"myfield_id": {
"terms": {
"field": "myfield_id",
"missing_bucket": true
}
}
}
]
}
}
},
"query": {
"bool": {
"must_not": [
{
"term": {
"is_reversed": {
"value": 1
}
}
}
]
}
},
"size": 65533
}
I have problem in is_reversed part. also I implemented composite and aggregationsparts, but cant combine them in my_buckets.
Thank you!
CodePudding user response:
You need to use terms query and below is way to add aggregation in my_bucket:
List<FieldValue> values = new ArrayList<>();
values.add(FieldValue.of(1));
values.add(FieldValue.of(2));
Query byReveredTransactionType = TermsQuery.of(t -> t.field("is_reversed").terms(v -> v.value(values)))._toQuery();
Map<String, CompositeAggregationSource> cas = new HashMap<>();
cas.put("myfield_id",CompositeAggregationSource.of(c -> c.terms(t -> t.field("myfield_id").missingBucket(true))));
SearchRequest req = SearchRequest.of(r -> r.query(q -> q.bool(b -> b.mustNot(byReveredTransactionType))).aggregations("my_buckets", Aggregation.of(a -> a.composite(c -> c.sources(cas)).aggregations("sum",Aggregation.of(a2 -> a2.sum(s -> s.field("amount")))))));
StringWriter writer = new StringWriter();
JsonGenerator generator = JacksonJsonProvider.provider().createGenerator(writer);
req.serialize(generator, new JacksonJsonpMapper());
generator.flush();
System.out.println(writer.toString());