Search in sources :

Example 61 with Aggregate

use of org.apache.calcite.rel.core.Aggregate in project flink by apache.

the class RelTimeIndicatorConverter method gatherIndicesToMaterialize.

private Set<Integer> gatherIndicesToMaterialize(Aggregate agg, RelNode newInput) {
    List<RelDataType> inputFieldTypes = RelOptUtil.getFieldTypeList(newInput.getRowType());
    Predicate<Integer> isTimeIndicator = idx -> isTimeIndicatorType(inputFieldTypes.get(idx));
    // add arguments of agg calls
    Set<Integer> aggCallArgs = agg.getAggCallList().stream().map(AggregateCall::getArgList).flatMap(List::stream).filter(isTimeIndicator).collect(Collectors.toSet());
    FlinkRelMetadataQuery fmq = FlinkRelMetadataQuery.reuseOrCreate(agg.getCluster().getMetadataQuery());
    RelWindowProperties windowProps = fmq.getRelWindowProperties(newInput);
    // add grouping sets
    Set<Integer> groupSets = agg.getGroupSets().stream().map(grouping -> {
        if (windowProps != null && groupingContainsWindowStartEnd(grouping, windowProps)) {
            // of window_time column
            return grouping.except(windowProps.getWindowTimeColumns());
        } else {
            return grouping;
        }
    }).flatMap(set -> set.asList().stream()).filter(isTimeIndicator).collect(Collectors.toSet());
    Set<Integer> timeIndicatorIndices = new HashSet<>(aggCallArgs);
    timeIndicatorIndices.addAll(groupSets);
    return timeIndicatorIndices;
}
Also used : WindowUtil.groupingContainsWindowStartEnd(org.apache.flink.table.planner.plan.utils.WindowUtil.groupingContainsWindowStartEnd) RexProgram(org.apache.calcite.rex.RexProgram) Tuple2(org.apache.flink.api.java.tuple.Tuple2) FlinkLogicalWindowAggregate(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalWindowAggregate) LogicalTableModify(org.apache.calcite.rel.logical.LogicalTableModify) FlinkLogicalLegacySink(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalLegacySink) FlinkLogicalDistribution(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalDistribution) FlinkLogicalIntersect(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalIntersect) TemporalJoinUtil(org.apache.flink.table.planner.plan.utils.TemporalJoinUtil) RexPatternFieldRef(org.apache.calcite.rex.RexPatternFieldRef) RexNode(org.apache.calcite.rex.RexNode) Map(java.util.Map) FlinkLogicalSnapshot(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSnapshot) LocalZonedTimestampType(org.apache.flink.table.types.logical.LocalZonedTimestampType) FlinkLogicalMinus(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalMinus) Predicate(java.util.function.Predicate) FlinkLogicalTableFunctionScan(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableFunctionScan) FlinkLogicalRank(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalRank) Set(java.util.Set) FlinkLogicalJoin(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalJoin) Preconditions(org.apache.flink.util.Preconditions) Collectors(java.util.stream.Collectors) FlinkLogicalValues(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalValues) RexInputRef(org.apache.calcite.rex.RexInputRef) List(java.util.List) FlinkTypeFactory.isTimeIndicatorType(org.apache.flink.table.planner.calcite.FlinkTypeFactory.isTimeIndicatorType) LogicalType(org.apache.flink.table.types.logical.LogicalType) SqlStdOperatorTable(org.apache.calcite.sql.fun.SqlStdOperatorTable) FlinkLogicalSink(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSink) RexLocalRef(org.apache.calcite.rex.RexLocalRef) ValidationException(org.apache.flink.table.api.ValidationException) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) FlinkTypeFactory.isRowtimeIndicatorType(org.apache.flink.table.planner.calcite.FlinkTypeFactory.isRowtimeIndicatorType) FlinkLogicalSort(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort) FlinkLogicalOverAggregate(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalOverAggregate) RexCall(org.apache.calcite.rex.RexCall) IntStream(java.util.stream.IntStream) TableScan(org.apache.calcite.rel.core.TableScan) LogicalCalc(org.apache.calcite.rel.logical.LogicalCalc) FlinkLogicalMatch(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalMatch) FlinkLogicalUnion(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalUnion) SetOp(org.apache.calcite.rel.core.SetOp) RelWindowProperties(org.apache.flink.table.planner.plan.trait.RelWindowProperties) RelOptUtil(org.apache.calcite.plan.RelOptUtil) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) MatchUtil.isFinalOnMatchTimeIndicator(org.apache.flink.table.planner.plan.utils.MatchUtil.isFinalOnMatchTimeIndicator) TimestampType(org.apache.flink.table.types.logical.TimestampType) Pair(org.apache.calcite.util.Pair) FlinkLogicalAggregate(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalAggregate) TimeIndicatorRelDataType(org.apache.flink.table.planner.plan.schema.TimeIndicatorRelDataType) SqlOperator(org.apache.calcite.sql.SqlOperator) SingleRel(org.apache.calcite.rel.SingleRel) RelCollations(org.apache.calcite.rel.RelCollations) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) FlinkRelMetadataQuery(org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery) RexBuilder(org.apache.calcite.rex.RexBuilder) FlinkTypeFactory.isProctimeIndicatorType(org.apache.flink.table.planner.calcite.FlinkTypeFactory.isProctimeIndicatorType) TableException(org.apache.flink.table.api.TableException) FlinkLogicalTableAggregate(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableAggregate) FlinkLogicalCalc(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCalc) FlinkLogicalWindowTableAggregate(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalWindowTableAggregate) FlinkLogicalExpand(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalExpand) RelNode(org.apache.calcite.rel.RelNode) Aggregate(org.apache.calcite.rel.core.Aggregate) JoinUtil(org.apache.flink.table.planner.plan.utils.JoinUtil) RelHomogeneousShuttle(org.apache.calcite.rel.RelHomogeneousShuttle) RexProgramBuilder(org.apache.calcite.rex.RexProgramBuilder) FlinkSqlOperatorTable(org.apache.flink.table.planner.functions.sql.FlinkSqlOperatorTable) FlinkLogicalWatermarkAssigner(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalWatermarkAssigner) AggregateCall(org.apache.calcite.rel.core.AggregateCall) RexShuttle(org.apache.calcite.rex.RexShuttle) FlinkLogicalCorrelate(org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalCorrelate) Collections(java.util.Collections) RelWindowProperties(org.apache.flink.table.planner.plan.trait.RelWindowProperties) TimeIndicatorRelDataType(org.apache.flink.table.planner.plan.schema.TimeIndicatorRelDataType) RelDataType(org.apache.calcite.rel.type.RelDataType) List(java.util.List) ArrayList(java.util.ArrayList) FlinkRelMetadataQuery(org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery) HashSet(java.util.HashSet)

Example 62 with Aggregate

use of org.apache.calcite.rel.core.Aggregate in project druid by druid-io.

the class DruidQuery method computeAggregations.

/**
 * Returns aggregations corresponding to {@code aggregate.getAggCallList()}, in the same order.
 *
 * @param partialQuery          partial query
 * @param plannerContext        planner context
 * @param rowSignature          source row signature
 * @param virtualColumnRegistry re-usable virtual column references
 * @param rexBuilder            calcite RexBuilder
 * @param finalizeAggregations  true if this query should include explicit finalization for all of its
 *                              aggregators, where required. Useful for subqueries where Druid's native query layer
 *                              does not do this automatically.
 *
 * @return aggregations
 *
 * @throws CannotBuildQueryException if dimensions cannot be computed
 */
private static List<Aggregation> computeAggregations(final PartialDruidQuery partialQuery, final PlannerContext plannerContext, final RowSignature rowSignature, final VirtualColumnRegistry virtualColumnRegistry, final RexBuilder rexBuilder, final boolean finalizeAggregations) {
    final Aggregate aggregate = Preconditions.checkNotNull(partialQuery.getAggregate());
    final List<Aggregation> aggregations = new ArrayList<>();
    final String outputNamePrefix = Calcites.findUnusedPrefixForDigits("a", rowSignature.getColumnNames());
    for (int i = 0; i < aggregate.getAggCallList().size(); i++) {
        final String aggName = outputNamePrefix + i;
        final AggregateCall aggCall = aggregate.getAggCallList().get(i);
        final Aggregation aggregation = GroupByRules.translateAggregateCall(plannerContext, rowSignature, virtualColumnRegistry, rexBuilder, partialQuery.getSelectProject(), aggregations, aggName, aggCall, finalizeAggregations);
        if (aggregation == null) {
            if (null == plannerContext.getPlanningError()) {
                plannerContext.setPlanningError("Aggregation [%s] is not supported", aggCall);
            }
            throw new CannotBuildQueryException(aggregate, aggCall);
        }
        aggregations.add(aggregation);
    }
    return aggregations;
}
Also used : Aggregation(org.apache.druid.sql.calcite.aggregation.Aggregation) AggregateCall(org.apache.calcite.rel.core.AggregateCall) IntArrayList(it.unimi.dsi.fastutil.ints.IntArrayList) ArrayList(java.util.ArrayList) Aggregate(org.apache.calcite.rel.core.Aggregate)

Example 63 with Aggregate

use of org.apache.calcite.rel.core.Aggregate in project druid by druid-io.

the class DruidQuery method computeSubtotals.

/**
 * Builds a {@link Subtotals} object based on {@link Aggregate#getGroupSets()}.
 */
private static Subtotals computeSubtotals(final PartialDruidQuery partialQuery, final RowSignature rowSignature) {
    final Aggregate aggregate = partialQuery.getAggregate();
    // dimBitMapping maps from input field position to group set position (dimension number).
    final int[] dimBitMapping;
    if (partialQuery.getSelectProject() != null) {
        dimBitMapping = new int[partialQuery.getSelectProject().getRowType().getFieldCount()];
    } else {
        dimBitMapping = new int[rowSignature.size()];
    }
    int i = 0;
    for (int dimBit : aggregate.getGroupSet()) {
        dimBitMapping[dimBit] = i++;
    }
    // Use dimBitMapping to remap groupSets (which is input-field-position based) into subtotals (which is
    // dimension-list-position based).
    final List<IntList> subtotals = new ArrayList<>();
    for (ImmutableBitSet groupSet : aggregate.getGroupSets()) {
        final IntList subtotal = new IntArrayList();
        for (int dimBit : groupSet) {
            subtotal.add(dimBitMapping[dimBit]);
        }
        subtotals.add(subtotal);
    }
    return new Subtotals(subtotals);
}
Also used : ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) IntArrayList(it.unimi.dsi.fastutil.ints.IntArrayList) ArrayList(java.util.ArrayList) Aggregate(org.apache.calcite.rel.core.Aggregate) IntArrayList(it.unimi.dsi.fastutil.ints.IntArrayList) IntList(it.unimi.dsi.fastutil.ints.IntList)

Example 64 with Aggregate

use of org.apache.calcite.rel.core.Aggregate in project beam by apache.

the class BeamAggregationRule method onMatch.

@Override
public void onMatch(RelOptRuleCall call) {
    final Aggregate aggregate = call.rel(0);
    final Project project = call.rel(1);
    if (aggregate.getGroupType() != Aggregate.Group.SIMPLE) {
        return;
    }
    RelNode x = updateWindow(aggregate, project);
    if (x == null) {
        // Non-windowed case should be handled by the BeamBasicAggregationRule
        return;
    }
    call.transformTo(x);
}
Also used : Project(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.core.Project) RelNode(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelNode) Aggregate(org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.core.Aggregate)

Example 65 with Aggregate

use of org.apache.calcite.rel.core.Aggregate in project druid by druid-io.

the class ProjectAggregatePruneUnusedCallRule method onMatch.

@Override
public void onMatch(final RelOptRuleCall call) {
    final Project project = call.rel(0);
    final Aggregate aggregate = call.rel(1);
    final ImmutableBitSet projectBits = RelOptUtil.InputFinder.bits(project.getChildExps(), null);
    final int fieldCount = aggregate.getGroupCount() + aggregate.getAggCallList().size();
    if (fieldCount != aggregate.getRowType().getFieldCount()) {
        throw new ISE("Expected[%s] to have[%s] fields but it had[%s]", aggregate, fieldCount, aggregate.getRowType().getFieldCount());
    }
    final ImmutableBitSet callsToKeep = projectBits.intersect(ImmutableBitSet.range(aggregate.getGroupCount(), fieldCount));
    if (callsToKeep.cardinality() < aggregate.getAggCallList().size()) {
        // There are some aggregate calls to prune.
        final List<AggregateCall> newAggregateCalls = new ArrayList<>();
        for (int i : callsToKeep) {
            newAggregateCalls.add(aggregate.getAggCallList().get(i - aggregate.getGroupCount()));
        }
        final Aggregate newAggregate = aggregate.copy(aggregate.getTraitSet(), aggregate.getInput(), aggregate.getGroupSet(), aggregate.getGroupSets(), newAggregateCalls);
        // Project that will match the old Aggregate in its row type, so we can layer the original "project" on top.
        final List<RexNode> fixUpProjects = new ArrayList<>();
        final RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder();
        // Project the group set unchanged.
        for (int i = 0; i < aggregate.getGroupCount(); i++) {
            fixUpProjects.add(rexBuilder.makeInputRef(newAggregate, i));
        }
        // Replace pruned-out aggregators with NULLs.
        for (int i = aggregate.getGroupCount(), j = aggregate.getGroupCount(); i < fieldCount; i++) {
            if (callsToKeep.get(i)) {
                fixUpProjects.add(rexBuilder.makeInputRef(newAggregate, j++));
            } else {
                fixUpProjects.add(rexBuilder.makeNullLiteral(aggregate.getRowType().getFieldList().get(i).getType()));
            }
        }
        call.transformTo(call.builder().push(newAggregate).project(fixUpProjects).project(project.getChildExps()).build());
        call.getPlanner().setImportance(project, 0.0);
    }
}
Also used : AggregateCall(org.apache.calcite.rel.core.AggregateCall) Project(org.apache.calcite.rel.core.Project) ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) ArrayList(java.util.ArrayList) RexBuilder(org.apache.calcite.rex.RexBuilder) ISE(org.apache.druid.java.util.common.ISE) Aggregate(org.apache.calcite.rel.core.Aggregate) RexNode(org.apache.calcite.rex.RexNode)

Aggregations

Aggregate (org.apache.calcite.rel.core.Aggregate)63 RelNode (org.apache.calcite.rel.RelNode)34 AggregateCall (org.apache.calcite.rel.core.AggregateCall)30 ArrayList (java.util.ArrayList)29 RexNode (org.apache.calcite.rex.RexNode)25 LogicalAggregate (org.apache.calcite.rel.logical.LogicalAggregate)23 ImmutableBitSet (org.apache.calcite.util.ImmutableBitSet)20 RelBuilder (org.apache.calcite.tools.RelBuilder)19 RexBuilder (org.apache.calcite.rex.RexBuilder)15 HashMap (java.util.HashMap)14 Project (org.apache.calcite.rel.core.Project)14 RexInputRef (org.apache.calcite.rex.RexInputRef)13 RelMetadataQuery (org.apache.calcite.rel.metadata.RelMetadataQuery)12 Filter (org.apache.calcite.rel.core.Filter)11 RelDataType (org.apache.calcite.rel.type.RelDataType)11 Join (org.apache.calcite.rel.core.Join)10 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)10 HiveAggregate (org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveAggregate)9 List (java.util.List)8 ImmutableList (com.google.common.collect.ImmutableList)7