Create a new aggregating set expression using a backing TreeSet

@param groupExpression values for this expression will be accumulated into a set
@return wrapper expression
436405
public static <E, F extends Comparable<? super F>> GroupExpression<E, SortedSet<F>> sortedSet(GroupExpression<E, F> groupExpression) {
        return new MixinGroupExpression<E, F, SortedSet<F>>(groupExpression, GSet.createSorted(groupExpression));
    }
714468
public ApiResponse createGroup(String groupPath, String groupTitle) {
     return createGroup(groupPath, groupTitle, null);  
    }
668664
public AggregationBuilder makeGroupAgg(Field field) throws SqlParseException {

        //zhongshu-comment script类型的MethodField
        if (field instanceof MethodField && field.getName().equals("script")) {
            MethodField methodField = (MethodField) field;
                /*
                TermsAggregationBuilder termsBuilder的样例：
                来自这条sql的group by子句的gg字段解析结果：
                select a,case when c='1' then 'haha' when c='2' then 'book' else 'hbhb' end as gg from tbl_a group by a,gg
                {
                    "gg":{ //aggs的名字就叫gg
                        "terms":{
                            "script":{
                                "source":"if((doc['c'].value=='1')){'haha'} else if((doc['c'].value=='2')){'book'} else {'hbhb'}",
                                "lang":"painless"
                            },
                            "size":10,
                            "min_doc_count":1,
                            "shard_min_doc_count":0,
                            "show_term_doc_count_error":false,
                            "order":[
                                {
                                    "_count":"desc"
                                },
                                {
                                    "_key":"asc"
                                }
                            ]
                        }
                    }
                }
             */
            TermsAggregationBuilder termsBuilder = AggregationBuilders.terms(methodField.getAlias()).script(new Script(methodField.getParams().get(1).value.toString()));

            //question 这里为什么要将这些信息加到groupMap中？
            groupMap.put(methodField.getAlias(), new KVValue("KEY", termsBuilder));

            return termsBuilder;
        }

        //zhongshu-comment filter类型的MethodField
        if (field instanceof MethodField) {

            MethodField methodField = (MethodField) field;
            if (methodField.getName().equals("filter")) {
                Map<String, Object> paramsAsMap = methodField.getParamsAsMap();
                Where where = (Where) paramsAsMap.get("where");
                return AggregationBuilders.filter(paramsAsMap.get("alias").toString(),
                        QueryMaker.explan(where));
            }
            return makeRangeGroup(methodField);
        } else {
            TermsAggregationBuilder termsBuilder = AggregationBuilders.terms(field.getName()).field(field.getName());
            groupMap.put(field.getName(), new KVValue("KEY", termsBuilder));
            return termsBuilder;
        }
    }
322824
@Override
    public ListT<W,Vector<T>> grouped(final int groupSize) {

        return (ListT<W,Vector<T>>) FoldableTransformerSeq.super.grouped(groupSize);
    }
182463
@SuppressWarnings("unchecked")
    public <V> ResultTransformer<Map<K, V>> as(Expression<V> expression) {
        final Expression<V> lookup = getLookup(expression);
        return new GroupByMap<K, V>(key, expression) {
            @Override
            protected Map<K, V> transform(Map<K, Group> groups) {
                Map<K, V> results = new LinkedHashMap<K, V>((int) Math.ceil(groups.size() / 0.75), 0.75f);
                for (Map.Entry<K, Group> entry : groups.entrySet()) {
                    results.put(entry.getKey(), entry.getValue().getOne(lookup));
                }
                return results;
            }
        };
    }
802090
public static <E, F> AbstractGroupExpression<E, List<F>> list(GroupExpression<E, F> groupExpression) {
        return new MixinGroupExpression<E, F, List<F>>(groupExpression, new GList<F>(groupExpression));
    }
628081
public static <K extends Comparable<? super K>, V, U> AbstractGroupExpression<Pair<K, V>, SortedMap<K, U>> sortedMap(Expression<K> key,
                                                                                                                         GroupExpression<V, U> value) {
        return sortedMap(new GOne<K>(key), value);
    }
16706
public final hqlParser.aggregateDistinctAll_return aggregateDistinctAll() throws RecognitionException {
		hqlParser.aggregateDistinctAll_return retval = new hqlParser.aggregateDistinctAll_return();
		retval.start = input.LT(1);

		CommonTree root_0 = null;

		Token set271=null;
		ParserRuleReturnScope path272 =null;
		ParserRuleReturnScope collectionExpr273 =null;

		CommonTree set271_tree=null;

		try {
			// hql.g:644:2: ( ( ( DISTINCT | ALL )? ( path | collectionExpr ) ) )
			// hql.g:644:4: ( ( DISTINCT | ALL )? ( path | collectionExpr ) )
			{
			root_0 = (CommonTree)adaptor.nil();


			// hql.g:644:4: ( ( DISTINCT | ALL )? ( path | collectionExpr ) )
			// hql.g:644:6: ( DISTINCT | ALL )? ( path | collectionExpr )
			{
			// hql.g:644:6: ( DISTINCT | ALL )?
			int alt97=2;
			int LA97_0 = input.LA(1);
			if ( (LA97_0==ALL||LA97_0==DISTINCT) ) {
				alt97=1;
			}
			switch (alt97) {
				case 1 :
					// hql.g:
					{
					set271=input.LT(1);
					if ( input.LA(1)==ALL||input.LA(1)==DISTINCT ) {
						input.consume();
						adaptor.addChild(root_0, adaptor.create(set271));
						state.errorRecovery=false;
					}
					else {
						MismatchedSetException mse = new MismatchedSetException(null,input);
						throw mse;
					}
					}
					break;

			}

			// hql.g:644:26: ( path | collectionExpr )
			int alt98=2;
			int LA98_0 = input.LA(1);
			if ( (LA98_0==IDENT) ) {
				alt98=1;
			}
			else if ( (LA98_0==ELEMENTS||LA98_0==INDICES) ) {
				alt98=2;
			}

			else {
				NoViableAltException nvae =
					new NoViableAltException("", 98, 0, input);
				throw nvae;
			}

			switch (alt98) {
				case 1 :
					// hql.g:644:28: path
					{
					pushFollow(FOLLOW_path_in_aggregateDistinctAll3230);
					path272=path();
					state._fsp--;

					adaptor.addChild(root_0, path272.getTree());

					}
					break;
				case 2 :
					// hql.g:644:35: collectionExpr
					{
					pushFollow(FOLLOW_collectionExpr_in_aggregateDistinctAll3234);
					collectionExpr273=collectionExpr();
					state._fsp--;

					adaptor.addChild(root_0, collectionExpr273.getTree());

					}
					break;

			}

			}

			}

			retval.stop = input.LT(-1);

			retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
			adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
			retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
		}
		finally {
			// do for sure before leaving
		}
		return retval;
	}
73937
public static <E extends Comparable<? super E>> AbstractGroupExpression<E, E> max(Expression<E> expression) {
        return new GMax<E>(expression);
    }
722796
function parseGroupExpression() {
        var expr, expressions, startToken, i, params = [];

        expect('(');

        if (match(')')) {
            lex();
            if (!match('=>')) {
                expect('=>');
            }
            return {
                type: PlaceHolders.ArrowParameterPlaceHolder,
                params: [],
                rawParams: []
            };
        }

        startToken = lookahead;
        if (match('...')) {
            expr = parseRestElement(params);
            expect(')');
            if (!match('=>')) {
                expect('=>');
            }
            return {
                type: PlaceHolders.ArrowParameterPlaceHolder,
                params: [expr]
            };
        }

        isBindingElement = true;
        expr = inheritCoverGrammar(parseAssignmentExpression);

        if (match(',')) {
            isAssignmentTarget = false;
            expressions = [expr];

            while (startIndex < length) {
                if (!match(',')) {
                    break;
                }
                lex();

                if (match('...')) {
                    if (!isBindingElement) {
                        throwUnexpectedToken(lookahead);
                    }
                    expressions.push(parseRestElement(params));
                    expect(')');
                    if (!match('=>')) {
                        expect('=>');
                    }
                    isBindingElement = false;
                    for (i = 0; i < expressions.length; i++) {
                        reinterpretExpressionAsPattern(expressions[i]);
                    }
                    return {
                        type: PlaceHolders.ArrowParameterPlaceHolder,
                        params: expressions
                    };
                }

                expressions.push(inheritCoverGrammar(parseAssignmentExpression));
            }

            expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
        }


        expect(')');

        if (match('=>')) {
            if (expr.type === Syntax.Identifier && expr.name === 'yield') {
                return {
                    type: PlaceHolders.ArrowParameterPlaceHolder,
                    params: [expr]
                };
            }

            if (!isBindingElement) {
                throwUnexpectedToken(lookahead);
            }

            if (expr.type === Syntax.SequenceExpression) {
                for (i = 0; i < expr.expressions.length; i++) {
                    reinterpretExpressionAsPattern(expr.expressions[i]);
                }
            } else {
                reinterpretExpressionAsPattern(expr);
            }

            expr = {
                type: PlaceHolders.ArrowParameterPlaceHolder,
                params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr]
            };
        }
        isBindingElement = false;
        return expr;
    }
61118
public static <T, K, R> Map<R, List<T>> toMapGroupBy( Stream<T> stream, Function<T, R> groupingFunction ) {
        return stream.collect(Collectors.groupingBy(groupingFunction));
        // to get a set: Collectors.groupingBy(groupingFunction, Collectors.toSet())
    }
902312
public static Aggregation translateAggregateCall(
      final PlannerContext plannerContext,
      final DruidQuerySignature querySignature,
      final RexBuilder rexBuilder,
      final Project project,
      final List<Aggregation> existingAggregations,
      final String name,
      final AggregateCall call,
      final boolean finalizeAggregations
  )
  {
    final DimFilter filter;

    if (call.filterArg >= 0) {
      // AGG(xxx) FILTER(WHERE yyy)
      if (project == null) {
        // We need some kind of projection to support filtered aggregations.
        return null;
      }

      final RexNode expression = project.getChildExps().get(call.filterArg);
      final DimFilter nonOptimizedFilter = Expressions.toFilter(plannerContext, querySignature, expression);
      if (nonOptimizedFilter == null) {
        return null;
      } else {
        filter = Filtration.create(nonOptimizedFilter).optimizeFilterOnly(querySignature).getDimFilter();
      }
    } else {
      filter = null;
    }

    final SqlAggregator sqlAggregator = plannerContext.getOperatorTable()
                                                      .lookupAggregator(call.getAggregation());

    if (sqlAggregator == null) {
      return null;
    }

    // Compute existingAggregations for SqlAggregator impls that want it.
    final List<Aggregation> existingAggregationsWithSameFilter = new ArrayList<>();
    for (Aggregation existingAggregation : existingAggregations) {
      if (filter == null) {
        final boolean doesMatch = existingAggregation.getAggregatorFactories().stream().noneMatch(
            factory -> factory instanceof FilteredAggregatorFactory
        );

        if (doesMatch) {
          existingAggregationsWithSameFilter.add(existingAggregation);
        }
      } else {
        final boolean doesMatch = existingAggregation.getAggregatorFactories().stream().allMatch(
            factory -> factory instanceof FilteredAggregatorFactory &&
                       ((FilteredAggregatorFactory) factory).getFilter().equals(filter)
        );

        if (doesMatch) {
          existingAggregationsWithSameFilter.add(
              Aggregation.create(
                  existingAggregation.getVirtualColumns(),
                  existingAggregation.getAggregatorFactories().stream()
                                     .map(factory -> ((FilteredAggregatorFactory) factory).getAggregator())
                                     .collect(Collectors.toList()),
                  existingAggregation.getPostAggregator()
              )
          );
        }
      }
    }

    final Aggregation retVal = sqlAggregator.toDruidAggregation(
        plannerContext,
        querySignature,
        rexBuilder,
        name, call, project, existingAggregationsWithSameFilter,
        finalizeAggregations
    );

    if (retVal == null) {
      return null;
    } else {
      // Check if this refers to the existingAggregationsWithSameFilter. If so, no need to apply the filter.
      if (isUsingExistingAggregation(retVal, existingAggregationsWithSameFilter)) {
        return retVal;
      } else {
        return retVal.filter(querySignature, filter);
      }
    }
  }
189819
public <V> ResultTransformer<CloseableIterator<V>> iterate(FactoryExpression<V> expression) {
        final FactoryExpression<V> transformation = FactoryExpressionUtils.wrap(expression);
        List<Expression<?>> args = transformation.getArgs();
        return new GroupByIterate<K, V>(key, args.toArray(new Expression<?>[args.size()])) {
            @Override
            protected V transform(Group group) {
                // XXX Isn't group.toArray() suitable here?
                List<Object> args = new ArrayList<Object>(groupExpressions.size() - 1);
                for (int i = 1; i < groupExpressions.size(); i++) {
                    args.add(group.getGroup(groupExpressions.get(i)));
                }
                return transformation.newInstance(args.toArray());
            }
        };
    }
203239
public static <E> AbstractGroupExpression<E, List<E>> list(Expression<E> expression) {
        return new GList<E>(expression);
    }
317751
public AggregationBuilder buildAggregation(KunderaQuery query, EntityMetadata entityMetadata, QueryBuilder filter)
    {
        SelectStatement selectStatement = query.getSelectStatement();

        // To apply filter for where clause
        AggregationBuilder aggregationBuilder = buildWhereAggregations(entityMetadata, filter);
        if (KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))
        {
            TermsBuilder termsBuilder = processGroupByClause(selectStatement.getGroupByClause(), entityMetadata, query);
            aggregationBuilder.subAggregation(termsBuilder);
        }
        else
        {
            if (KunderaQueryUtils.hasHaving(query.getJpqlExpression()))
            {
                logger.error("Identified having clause without group by, Throwing not supported operation Exception");
                throw new UnsupportedOperationException(
                        "Currently, Having clause without group by caluse is not supported.");
            }
            else
            {
                aggregationBuilder = (selectStatement != null) ? query.isAggregated() ? buildSelectAggregations(
                        aggregationBuilder, selectStatement, entityMetadata) : null : null;
            }
        }

        return aggregationBuilder;
    }
894500
public AggregationResult aggregate(String rAggregateFormula) throws DDFException {

    return mAggregationHandler.aggregate(AggregateField.fromSqlFieldSpecs(parseRAggregateFormula(rAggregateFormula)));
  }
336698
public AggGroupSet addGroupSet() {
        AggGroupSet aggGroupSet = new AggGroupSet();
        if (m_groupSetList == null) {
            m_groupSetList = new ArrayList<AggGroupSet>();
        }
        m_groupSetList.add(aggGroupSet);
        return aggGroupSet;
    }