Search in sources :

Example 21 with RelCollation

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelCollation in project flink by apache.

the class RankProcessStrategy method analyzeRankProcessStrategies.

/**
 * Gets {@link RankProcessStrategy} based on input, partitionKey and orderKey.
 */
static List<RankProcessStrategy> analyzeRankProcessStrategies(StreamPhysicalRel rank, ImmutableBitSet partitionKey, RelCollation orderKey) {
    FlinkRelMetadataQuery mq = (FlinkRelMetadataQuery) rank.getCluster().getMetadataQuery();
    List<RelFieldCollation> fieldCollations = orderKey.getFieldCollations();
    boolean isUpdateStream = !ChangelogPlanUtils.inputInsertOnly(rank);
    RelNode input = rank.getInput(0);
    if (isUpdateStream) {
        Set<ImmutableBitSet> upsertKeys = mq.getUpsertKeysInKeyGroupRange(input, partitionKey.toArray());
        if (upsertKeys == null || upsertKeys.isEmpty() || // upsert key should contains partition key
        upsertKeys.stream().noneMatch(k -> k.contains(partitionKey))) {
            // and we fall back to using retract rank
            return Collections.singletonList(RETRACT_STRATEGY);
        } else {
            FlinkRelMetadataQuery fmq = FlinkRelMetadataQuery.reuseOrCreate(mq);
            RelModifiedMonotonicity monotonicity = fmq.getRelModifiedMonotonicity(input);
            boolean isMonotonic = false;
            if (monotonicity != null && !fieldCollations.isEmpty()) {
                isMonotonic = fieldCollations.stream().allMatch(collation -> {
                    SqlMonotonicity fieldMonotonicity = monotonicity.fieldMonotonicities()[collation.getFieldIndex()];
                    RelFieldCollation.Direction direction = collation.direction;
                    if ((fieldMonotonicity == SqlMonotonicity.DECREASING || fieldMonotonicity == SqlMonotonicity.STRICTLY_DECREASING) && direction == RelFieldCollation.Direction.ASCENDING) {
                        // is decreasing
                        return true;
                    } else if ((fieldMonotonicity == SqlMonotonicity.INCREASING || fieldMonotonicity == SqlMonotonicity.STRICTLY_INCREASING) && direction == RelFieldCollation.Direction.DESCENDING) {
                        // is increasing
                        return true;
                    } else {
                        // it is monotonic
                        return fieldMonotonicity == SqlMonotonicity.CONSTANT;
                    }
                });
            }
            if (isMonotonic) {
                // TODO: choose a set of primary key
                return Arrays.asList(new UpdateFastStrategy(upsertKeys.iterator().next().toArray()), RETRACT_STRATEGY);
            } else {
                return Collections.singletonList(RETRACT_STRATEGY);
            }
        }
    } else {
        return Collections.singletonList(APPEND_FAST_STRATEGY);
    }
}
Also used : ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) SqlMonotonicity(org.apache.calcite.sql.validate.SqlMonotonicity) Arrays(java.util.Arrays) JsonCreator(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator) FlinkRelMetadataQuery(org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery) RelModifiedMonotonicity(org.apache.flink.table.planner.plan.trait.RelModifiedMonotonicity) JsonSubTypes(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonSubTypes) Set(java.util.Set) RelNode(org.apache.calcite.rel.RelNode) FlinkChangelogModeInferenceProgram(org.apache.flink.table.planner.plan.optimize.program.FlinkChangelogModeInferenceProgram) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) StringUtils(org.apache.commons.lang3.StringUtils) StreamPhysicalRel(org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalRel) JsonProperty(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty) JsonIgnore(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore) List(java.util.List) RelCollation(org.apache.calcite.rel.RelCollation) JsonTypeInfo(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeInfo) JsonIgnoreProperties(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnoreProperties) JsonTypeName(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeName) Collections(java.util.Collections) RelNode(org.apache.calcite.rel.RelNode) ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) SqlMonotonicity(org.apache.calcite.sql.validate.SqlMonotonicity) FlinkRelMetadataQuery(org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery) RelModifiedMonotonicity(org.apache.flink.table.planner.plan.trait.RelModifiedMonotonicity)

Example 22 with RelCollation

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelCollation in project hazelcast by hazelcast.

the class IndexResolver method buildCollationTrait.

/**
 * Builds a collation with collation fields re-mapped according to the table projections.
 *
 * @param scan  the logical map scan
 * @param index the index
 * @param ascs  the collation of index fields
 * @return the new collation trait
 */
private static RelCollation buildCollationTrait(FullScanLogicalRel scan, MapTableIndex index, List<Boolean> ascs) {
    if (index.getType() != SORTED) {
        return RelCollations.of(Collections.emptyList());
    }
    List<RelFieldCollation> fields = new ArrayList<>(index.getFieldOrdinals().size());
    HazelcastTable table = OptUtils.extractHazelcastTable(scan);
    // Extract those projections that are direct input field references. Only those can be used
    // for index access
    List<Integer> fieldProjects = table.getProjects().stream().filter(expr -> expr instanceof RexInputRef).map(inputRef -> ((RexInputRef) inputRef).getIndex()).collect(Collectors.toList());
    for (int i = 0; i < index.getFieldOrdinals().size(); ++i) {
        Integer indexFieldOrdinal = index.getFieldOrdinals().get(i);
        int remappedIndexFieldOrdinal = fieldProjects.indexOf(indexFieldOrdinal);
        if (remappedIndexFieldOrdinal == -1) {
            // The field is not used in the query
            break;
        }
        Direction direction = ascs.get(i) ? ASCENDING : DESCENDING;
        RelFieldCollation fieldCollation = new RelFieldCollation(remappedIndexFieldOrdinal, direction);
        fields.add(fieldCollation);
    }
    return RelCollations.of(fields);
}
Also used : RangeSet(com.google.common.collect.RangeSet) QueryDataTypeFamily(com.hazelcast.sql.impl.type.QueryDataTypeFamily) OptUtils.getCluster(com.hazelcast.jet.sql.impl.opt.OptUtils.getCluster) QueryParameterMetadata(com.hazelcast.sql.impl.QueryParameterMetadata) Collections.singletonList(java.util.Collections.singletonList) HazelcastTable(com.hazelcast.jet.sql.impl.schema.HazelcastTable) TypeConverters(com.hazelcast.query.impl.TypeConverters) RexUtil(org.apache.calcite.rex.RexUtil) RexNode(org.apache.calcite.rex.RexNode) Map(java.util.Map) IndexRangeFilter(com.hazelcast.sql.impl.exec.scan.index.IndexRangeFilter) QueryDataTypeUtils(com.hazelcast.sql.impl.type.QueryDataTypeUtils) HASH(com.hazelcast.config.IndexType.HASH) IndexEqualsFilter(com.hazelcast.sql.impl.exec.scan.index.IndexEqualsFilter) RexToExpressionVisitor(com.hazelcast.jet.sql.impl.opt.physical.visitor.RexToExpressionVisitor) PlanNodeFieldTypeProvider(com.hazelcast.sql.impl.plan.node.PlanNodeFieldTypeProvider) RelTraitSet(org.apache.calcite.plan.RelTraitSet) SqlKind(org.apache.calcite.sql.SqlKind) HazelcastTypeUtils(com.hazelcast.jet.sql.impl.validate.types.HazelcastTypeUtils) RexLiteral(org.apache.calcite.rex.RexLiteral) Collection(java.util.Collection) Range(com.google.common.collect.Range) Set(java.util.Set) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) Collectors(java.util.stream.Collectors) IndexInFilter(com.hazelcast.sql.impl.exec.scan.index.IndexInFilter) RexInputRef(org.apache.calcite.rex.RexInputRef) List(java.util.List) FullScanLogicalRel(com.hazelcast.jet.sql.impl.opt.logical.FullScanLogicalRel) BoundType(com.google.common.collect.BoundType) RelCollation(org.apache.calcite.rel.RelCollation) MapTableIndex(com.hazelcast.sql.impl.schema.map.MapTableIndex) TRUE(java.lang.Boolean.TRUE) RexCall(org.apache.calcite.rex.RexCall) OptUtils.createRelTable(com.hazelcast.jet.sql.impl.opt.OptUtils.createRelTable) Iterables(com.google.common.collect.Iterables) IndexFilterValue(com.hazelcast.sql.impl.exec.scan.index.IndexFilterValue) IndexFilter(com.hazelcast.sql.impl.exec.scan.index.IndexFilter) QueryDataType(com.hazelcast.sql.impl.type.QueryDataType) HashMap(java.util.HashMap) POSITIVE_INFINITY(com.hazelcast.query.impl.CompositeValue.POSITIVE_INFINITY) RelOptUtil(org.apache.calcite.plan.RelOptUtil) RelOptTable(org.apache.calcite.plan.RelOptTable) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) IndexType(com.hazelcast.config.IndexType) BiTuple(com.hazelcast.internal.util.BiTuple) Expression(com.hazelcast.sql.impl.expression.Expression) Nonnull(javax.annotation.Nonnull) ComparableIdentifiedDataSerializable(com.hazelcast.query.impl.ComparableIdentifiedDataSerializable) RelCollations(org.apache.calcite.rel.RelCollations) RexToExpression(com.hazelcast.jet.sql.impl.opt.physical.visitor.RexToExpression) RelDataType(org.apache.calcite.rel.type.RelDataType) FALSE(java.lang.Boolean.FALSE) HazelcastRelOptTable(com.hazelcast.jet.sql.impl.schema.HazelcastRelOptTable) RelCollationTraitDef(org.apache.calcite.rel.RelCollationTraitDef) SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) SORTED(com.hazelcast.config.IndexType.SORTED) Util.toList(com.hazelcast.jet.impl.util.Util.toList) RexBuilder(org.apache.calcite.rex.RexBuilder) OptUtils(com.hazelcast.jet.sql.impl.opt.OptUtils) IndexScanMapPhysicalRel(com.hazelcast.jet.sql.impl.opt.physical.IndexScanMapPhysicalRel) RelNode(org.apache.calcite.rel.RelNode) Direction(org.apache.calcite.rel.RelFieldCollation.Direction) ASCENDING(org.apache.calcite.rel.RelFieldCollation.Direction.ASCENDING) TreeMap(java.util.TreeMap) NEGATIVE_INFINITY(com.hazelcast.query.impl.CompositeValue.NEGATIVE_INFINITY) ConstantExpression(com.hazelcast.sql.impl.expression.ConstantExpression) DESCENDING(org.apache.calcite.rel.RelFieldCollation.Direction.DESCENDING) Collections(java.util.Collections) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) ArrayList(java.util.ArrayList) RexInputRef(org.apache.calcite.rex.RexInputRef) HazelcastTable(com.hazelcast.jet.sql.impl.schema.HazelcastTable) Direction(org.apache.calcite.rel.RelFieldCollation.Direction)

Example 23 with RelCollation

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelCollation in project hazelcast by hazelcast.

the class IndexResolver method createFullIndexScan.

/**
 * Creates an index scan without any filter.
 *
 * @param scan              the original scan operator
 * @param index             available indexes
 * @param ascs              the collation of index fields
 * @param nonEmptyCollation whether to filter out full index scan with no collation
 * @return index scan or {@code null}
 */
private static RelNode createFullIndexScan(FullScanLogicalRel scan, MapTableIndex index, List<Boolean> ascs, boolean nonEmptyCollation) {
    assert isIndexSupported(index);
    RexNode scanFilter = OptUtils.extractHazelcastTable(scan).getFilter();
    RelTraitSet traitSet = OptUtils.toPhysicalConvention(scan.getTraitSet());
    RelCollation relCollation = buildCollationTrait(scan, index, ascs);
    if (nonEmptyCollation && relCollation.getFieldCollations().size() == 0) {
        // Don't make a full scan with empty collation
        return null;
    }
    traitSet = OptUtils.traitPlus(traitSet, relCollation);
    HazelcastRelOptTable originalRelTable = (HazelcastRelOptTable) scan.getTable();
    HazelcastTable originalHazelcastTable = OptUtils.extractHazelcastTable(scan);
    RelOptTable newRelTable = createRelTable(originalRelTable.getDelegate().getQualifiedName(), originalHazelcastTable.withFilter(null), scan.getCluster().getTypeFactory());
    return new IndexScanMapPhysicalRel(scan.getCluster(), traitSet, newRelTable, index, null, null, scanFilter);
}
Also used : IndexScanMapPhysicalRel(com.hazelcast.jet.sql.impl.opt.physical.IndexScanMapPhysicalRel) RelCollation(org.apache.calcite.rel.RelCollation) HazelcastRelOptTable(com.hazelcast.jet.sql.impl.schema.HazelcastRelOptTable) RelTraitSet(org.apache.calcite.plan.RelTraitSet) RelOptTable(org.apache.calcite.plan.RelOptTable) HazelcastRelOptTable(com.hazelcast.jet.sql.impl.schema.HazelcastRelOptTable) HazelcastTable(com.hazelcast.jet.sql.impl.schema.HazelcastTable) RexNode(org.apache.calcite.rex.RexNode)

Example 24 with RelCollation

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelCollation in project hive by apache.

the class HiveSortJoinReduceRule method onMatch.

@Override
public void onMatch(RelOptRuleCall call) {
    final HiveSortLimit sortLimit = call.rel(0);
    final HiveJoin join = call.rel(1);
    RelNode inputLeft = join.getLeft();
    RelNode inputRight = join.getRight();
    // We create a new sort operator on the corresponding input
    if (join.getJoinType() == JoinRelType.LEFT) {
        inputLeft = sortLimit.copy(sortLimit.getTraitSet(), inputLeft, sortLimit.getCollation(), sortLimit.offset, sortLimit.fetch);
        ((HiveSortLimit) inputLeft).setRuleCreated(true);
    } else {
        // Adjust right collation
        final RelCollation rightCollation = RelCollationTraitDef.INSTANCE.canonize(RelCollations.shift(sortLimit.getCollation(), -join.getLeft().getRowType().getFieldCount()));
        inputRight = sortLimit.copy(sortLimit.getTraitSet().replace(rightCollation), inputRight, rightCollation, sortLimit.offset, sortLimit.fetch);
        ((HiveSortLimit) inputRight).setRuleCreated(true);
    }
    // We copy the join and the top sort operator
    RelNode result = join.copy(join.getTraitSet(), join.getCondition(), inputLeft, inputRight, join.getJoinType(), join.isSemiJoinDone());
    result = sortLimit.copy(sortLimit.getTraitSet(), result, sortLimit.getCollation(), sortLimit.offset, sortLimit.fetch);
    call.transformTo(result);
}
Also used : RelCollation(org.apache.calcite.rel.RelCollation) RelNode(org.apache.calcite.rel.RelNode) HiveSortLimit(org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveSortLimit) HiveJoin(org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveJoin)

Example 25 with RelCollation

use of org.apache.beam.vendor.calcite.v1_28_0.org.apache.calcite.rel.RelCollation in project hive by apache.

the class RelFieldTrimmer method trimChild.

/**
 * Trims the fields of an input relational expression.
 *
 * @param rel        Relational expression
 * @param input      Input relational expression, whose fields to trim
 * @param fieldsUsed Bitmap of fields needed by the consumer
 * @return New relational expression and its field mapping
 */
protected TrimResult trimChild(RelNode rel, RelNode input, final ImmutableBitSet fieldsUsed, Set<RelDataTypeField> extraFields) {
    final ImmutableBitSet.Builder fieldsUsedBuilder = fieldsUsed.rebuild();
    // Fields that define the collation cannot be discarded.
    final RelMetadataQuery mq = rel.getCluster().getMetadataQuery();
    final ImmutableList<RelCollation> collations = mq.collations(input);
    if (collations != null) {
        for (RelCollation collation : collations) {
            for (RelFieldCollation fieldCollation : collation.getFieldCollations()) {
                fieldsUsedBuilder.set(fieldCollation.getFieldIndex());
            }
        }
    }
    // fields.
    for (final CorrelationId correlation : rel.getVariablesSet()) {
        rel.accept(new CorrelationReferenceFinder() {

            protected RexNode handle(RexFieldAccess fieldAccess) {
                final RexCorrelVariable v = (RexCorrelVariable) fieldAccess.getReferenceExpr();
                if (v.id.equals(correlation)) {
                    fieldsUsedBuilder.set(fieldAccess.getField().getIndex());
                }
                return fieldAccess;
            }
        });
    }
    return dispatchTrimFields(input, fieldsUsedBuilder.build(), extraFields);
}
Also used : RelMetadataQuery(org.apache.calcite.rel.metadata.RelMetadataQuery) RexCorrelVariable(org.apache.calcite.rex.RexCorrelVariable) RelCollation(org.apache.calcite.rel.RelCollation) ImmutableBitSet(org.apache.calcite.util.ImmutableBitSet) CorrelationReferenceFinder(org.apache.calcite.sql2rel.CorrelationReferenceFinder) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) CorrelationId(org.apache.calcite.rel.core.CorrelationId) RexFieldAccess(org.apache.calcite.rex.RexFieldAccess) RexNode(org.apache.calcite.rex.RexNode)

Aggregations

RelCollation (org.apache.calcite.rel.RelCollation)83 RelNode (org.apache.calcite.rel.RelNode)40 RelTraitSet (org.apache.calcite.plan.RelTraitSet)37 RelFieldCollation (org.apache.calcite.rel.RelFieldCollation)33 RexNode (org.apache.calcite.rex.RexNode)24 ArrayList (java.util.ArrayList)19 RelDataType (org.apache.calcite.rel.type.RelDataType)17 RelOptCluster (org.apache.calcite.plan.RelOptCluster)15 ImmutableBitSet (org.apache.calcite.util.ImmutableBitSet)13 RelMetadataQuery (org.apache.calcite.rel.metadata.RelMetadataQuery)12 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)12 List (java.util.List)11 Sort (org.apache.calcite.rel.core.Sort)11 ImmutableList (com.google.common.collect.ImmutableList)8 RelDistribution (org.apache.calcite.rel.RelDistribution)8 RexInputRef (org.apache.calcite.rex.RexInputRef)8 Map (java.util.Map)7 Mappings (org.apache.calcite.util.mapping.Mappings)7 Supplier (com.google.common.base.Supplier)6 HashMap (java.util.HashMap)6