elasticsearchelasticsearch-java-api

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


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?


Solution

  • I discovered the answer, undocumented. The byte[] overload of setAggregations() will accept JSON. I hope this is helpful to others.

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