I want to create a searchResponse object with aggregation results for testing.
I have tried the following
SearchResponseSections section = new SearchResponseSections(null, null, .......);
The first parameter here is for hits which I don't want but the second parameter which accepts Aggregations.
Now I am not able to create custom Aggregations object with buckets.
Code to test is as follows:
public AutoCompleteResponseDto getAutoCompleteResponse(SearchResponse searchResponse, String field, int limit) {
Terms aggregation = searchResponse.getAggregations().get("typeAhead");
final Set<String> bucketKeys = aggregation.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(Collectors.toSet());
return AutoCompleteResponseDto.builder().totalCount(bucketKeys.size()).values(bucketKeys).field(field).build();
}
I have also tried creating SearchResponse using Json as follows:
public static List<NamedXContentRegistry.Entry> getDefaultNamedXContents() {
Map<String, ContextParser<Object, ? extends Aggregation>> map = new HashMap<>();
map.put(StringTerms.NAME, (p, c) -> ParsedStringTerms.fromXContent(p, (String) c));
return map.entrySet().stream().map(entry -> new NamedXContentRegistry.Entry(Aggregation.class, new ParseField(entry.getKey(), entry.getValue()))).collect(Collectors.toList());
}
public static SearchResponse getSearchResponse(String jsonString) {
try {
NamedXContentRegistry registry = new NamedXContentRegistry(getDefaultNamedXContents());
XContentParser parser = new JsonXContentParser(registry, new JsonFactory().createParser(jsonString));
return SearchResponse.fromXContent(parser);
} catch (Exception ex) {
}
return new SearchResponse();
}
I am calling the getSearchResponse(json) method with the following Json:
{
"took": 65,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"aggregations": {
"typeAhead": {
"buckets": [
{
"key": "1002312321",
"docCount": 31521
}
]
}
}
}
And getting the ParseException: [could not parse the aggregation keyed as [typeAhead]].
ElasticSearch version = 5.6.15
PS: Please ignore typo if any.
The issue got resolved by giving the aggregation key as terms#typeAhead in json instead of typeAhead only.
Aggregation key should be given as aggType#key And an entry for the given aggregation type should be registered in NamedXContentRegistry.