How to use the ElasticSearch Java API to build an Aggregation from JSON

Hi everyone,

My code has an ElasticSearch query and aggregations in JSON format, and wants to call the ElasticSearch Java API.

For the Query portion, I can use WrapperQuery to build the query from the JSON as so:

val query = Json.obj(
  "query_string" -> Json.obj("query" -> "*"))

val aggs = Json.obj(
  "gender" -> Json.obj("terms" -> Json.obj("field": "gender")),
  "age"    -> Json.obj("terms" -> Json.obj("field": "age")))

val aggsRequestBuilder = new SearchRequestBuilder(client)
  .setIndices(index())
  .setQuery(QueryBuilders.wrapperQuery(query.toString())
  .addAggregation(AggregationBuilders.???(aggs.toString())

But then, I also have the JSON for the aggregations and I don't see an AggregationsBuilder.wrapperAggregation() function that I can use to build aggregations object from JSON.

Am I missing something?

Best regards,

The Notorious Jon Skeet

Why not using the Aggregation API?

https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/_bucket_aggregations.html#java-aggs-bucket-terms

val aggsRequestBuilder = new SearchRequestBuilder(client)
  .setIndices(index())
  .setQuery(QueryBuilders.wrapperQuery(query.toString())
  .addAggregation(AggregationBuilders.terms("gender").field("gender"))
  .addAggregation(AggregationBuilders.terms("age").field("age"))
1 Like

Because the aggregations in our system are dynamic and I don't want to parse them.

I don't think you can.
You can probably pass the full query DSL as a string but not only the agg part.

I did not check the code though.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.

Updating this old thread as @monde shared with me a solution he found on SOF:

 val aggsRequestBuilder = new SearchRequestBuilder(client)
  .setIndices(index())
  .setQuery(QueryBuilders.wrapperQuery(query.toString())
  .setAggregations(agg.toString().getBytes())