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


#1

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


Add Json aggregation string to SearchRequestBuilder in java API
How to use the Java API to build an Aggregation from JSON in 6.2.4?
(David Pilato) #2

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"))

#3

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


(David Pilato) #4

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.


(system) #5

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


(David Pilato) #6

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())

How to use the Java API to build an Aggregation from JSON in 6.2.4?