I have an Elasticsearch nested aggregation query(below), that I am trying to implement in Java using the Elasticsearch Java API. The query counts keywords and sorts using the reversed_nested _count. The query works in dev tools and partly Java, the only I can not sort using the Java API using the reversed_count.
GET products/_search { "size": 0, "aggs": { "products": { "nested": { "path": "affectedProducts.seller" }, "aggs": { "filtered_nestedobjects": { "filter": { "term": { "affectedProducts.seller.onOrWith": false } }, "aggs": { "filter_products": { "terms": { "field": "affectedProducts.seller.vendor.keyword", "order": { "reversed_count": "desc" } }, "aggs": { "reversed_count": { "reverse_nested": {} } } } } } } } } }
How can I implement using the java API to sort using reversed_count? I have tried using BucketOrder.count button working.
Please help.
Thanks
public SearchRequest createSearchRequest() { final NestedAggregationBuilder vendor; vendor = nested("products_count", "affectedProducts.seller") .subAggregation(filter("running", termQuery("affectedProducts.seller.onOrWith", false)) .subAggregation(terms("filter_products").field("affectedProducts.seller.vendor.keyword").order(BucketOrder.count(false))) .subAggregation(reverseNested("vendors_reverse"))); return searchRequest("products") .aggregation( global(AGG) .subAggregation(vendor) ) // .sort(new Sortable().setSort("_count")) .page(limitTo(0)) .build(); }
ES Version: 7.10.6
Advertisement
Answer
I believe the error is that the reversed_count subAggs must be subaggregation of filter_products.
final NestedAggregationBuilder vendor; vendor = nested("products_count", "affectedProducts.seller") .subAggregation(filter("filtered_nestedobjects", termQuery("affectedProducts.seller.onOrWith", false)) .subAggregation(terms("filter_products").field("affectedProducts.seller.vendor.keyword") .order(BucketOrder.aggregation("reversed_count", false)) .subAggregation(reverseNested("reversed_count")))); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); SearchRequest searchRequest = new SearchRequest("products"); searchSourceBuilder.aggregation(vendor); searchRequest.source(searchSourceBuilder);