private static GroupingOperation buildGroupingExpressionWithSorting(String dedupField, int groupingHits,
                                                                        String summaryClass, Sorting sortSpec) {
        return new AllOperation()
            .setGroupBy(new AttributeValue(dedupField))
            .addOutput(new CountAggregator().setLabel(LABEL_COUNT))
            .setMax(groupingHits)
            .addOrderBy(createHitOrderingClause(sortSpec))
            .addChild(new EachOperation()
                .addChild(new AllOperation()
                    .setGroupBy(createGroupOrderingClause(sortSpec))
                    .addOrderBy(createHitOrderingClause(sortSpec))
                    .setMax(1)
                    .addChild(new EachOperation()
                        .setLabel(LABEL_GROUPS)
                        .addChild(new EachOperation()
                            .setLabel(LABEL_HITS)
                            .addOutput(summaryClass == null ? new SummaryValue() : new SummaryValue(summaryClass))))));
    }
Create the grouping expression when sorting is used for ordering
This grouping expression is more complicated and probably quite a bit heavier to execute.
See unit test for examples
container-search/src/main/java/com/yahoo/search/grouping/UniqueGroupingSearcher.java