code: private TermsBuilder processGroupByClause(Expression expression, EntityMetadata entityMetadata, KunderaQuery query)
      {
          MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                  entityMetadata.getPersistenceUnit());
          Expression groupByClause = ((GroupByClause) expression).getGroupByItems();
  
          if (groupByClause instanceof CollectionExpression)
          {
              logger.error("More than one item found in group by clause.");
              throw new UnsupportedOperationException("Currently, Group By on more than one field is not supported.");
          }
  
          SelectStatement selectStatement = query.getSelectStatement();
  
          // To apply terms and tophits aggregation to serve group by
          String jPAField = KunderaCoreUtils.getJPAColumnName(groupByClause.toParsedText(), entityMetadata, metaModel);
          TermsBuilder termsBuilder = AggregationBuilders.terms(ESConstants.GROUP_BY).field(jPAField).size(0);
  
          // Hard coded value for a max number of record that a group can contain.
          TopHitsBuilder topHitsBuilder = getTopHitsAggregation(selectStatement, null, entityMetadata);
          termsBuilder.subAggregation(topHitsBuilder);
  
          // To apply the metric aggregations (Min, max... etc) in select clause
          buildSelectAggregations(termsBuilder, query.getSelectStatement(), entityMetadata);
  
          if (KunderaQueryUtils.hasHaving(query.getJpqlExpression()))
          {
              addHavingClause(((HavingClause) selectStatement.getHavingClause()).getConditionalExpression(),
                      termsBuilder, entityMetadata);
          }
  
          if (KunderaQueryUtils.hasOrderBy(query.getJpqlExpression()))
          {
              processOrderByClause(termsBuilder, KunderaQueryUtils.getOrderByClause(query.getJpqlExpression()),
                      groupByClause, entityMetadata);
          }
  
          return termsBuilder;
      }
docs: Process group by clause.
  
  @param expression
  the expression
  @param entityMetadata
  the entity metadata
  @param query
  the query
  @return the terms builder