0

I have the following Elasticsearch get query:

GET /...
{
   "size":"0",
   "aggs" : {
      "locations" : {
         "terms" : { "field" : "locationid.keyword" }
      }
   }
}

which works on console as it should. But the goal is to have this query programmatic via the Java API. I'm using Spring Boor with ElasticSearchRepository:

@Query("{\"size\" : \"0\" , \"aggs\" : {\"locations\" : {\"terms\" : { \"field\" : \"locationid.keyword\" }}}}")
List<Bucket> findDistinctLocationids();

So, now my problem is the following Exception:

ParsingException[size] query malformed, no start_object after query name

The error message is clear but which annotation or is useful for this case instead of @Query? Or is there any other way to retrive distinct records?

1

1 Answer 1

1

So, after some hours of try and error i found a solution based on @Vals comment. First, i set up a search which gives me a SearchResponse:

final SearchResponse sr = client.prepareSearch("index").setTypes("type").setQuery(QueryBuilders.matchAllQuery()).setSearchType(SearchType.DEFAULT).addAggregation(
            AggregationBuilders.terms("field").field("locationid.keyword")).execute().actionGet();

From this response i receive a Terms object which holds the results in its Bucktes:

final Terms locations = sr.getAggregations().get("field");
for (final Terms.Bucket entry : locations.getBuckets()) {
    System.out.println(entry.getKey());
    System.out.println(entry.getDocCount());
}

with exactly the result as in console is given.

Sign up to request clarification or add additional context in comments.

1 Comment

how would you do in case you wanna group by (aggregate) and the same time filter (query a filed by value) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.