Search in sources :

Example 1 with FunctionEx

use of com.hazelcast.function.FunctionEx in project hazelcast by hazelcast.

the class SlidingWindow method windowPolicyProvider.

public final FunctionEx<ExpressionEvalContext, SlidingWindowPolicy> windowPolicyProvider() {
    QueryParameterMetadata parameterMetadata = ((HazelcastRelOptCluster) getCluster()).getParameterMetadata();
    RexToExpressionVisitor visitor = new RexToExpressionVisitor(FAILING_FIELD_TYPE_PROVIDER, parameterMetadata);
    if (operator() == HazelcastSqlOperatorTable.TUMBLE) {
        Expression<?> windowSizeExpression = operand(2).accept(visitor);
        return context -> tumblingWinPolicy(WindowUtils.extractMillis(windowSizeExpression, context));
    } else if (operator() == HazelcastSqlOperatorTable.HOP) {
        Expression<?> windowSizeExpression = operand(2).accept(visitor);
        Expression<?> slideSizeExpression = operand(3).accept(visitor);
        return context -> slidingWinPolicy(WindowUtils.extractMillis(windowSizeExpression, context), WindowUtils.extractMillis(slideSizeExpression, context));
    } else {
        throw new IllegalArgumentException();
    }
}
Also used : SlidingWindowPolicy.slidingWinPolicy(com.hazelcast.jet.core.SlidingWindowPolicy.slidingWinPolicy) QueryParameterMetadata(com.hazelcast.sql.impl.QueryParameterMetadata) FAILING_FIELD_TYPE_PROVIDER(com.hazelcast.sql.impl.plan.node.PlanNodeFieldTypeProvider.FAILING_FIELD_TYPE_PROVIDER) SlidingWindowPolicy(com.hazelcast.jet.core.SlidingWindowPolicy) HazelcastRelOptCluster(org.apache.calcite.plan.HazelcastRelOptCluster) RelColumnMapping(org.apache.calcite.rel.metadata.RelColumnMapping) RexNode(org.apache.calcite.rex.RexNode) SqlOperator(org.apache.calcite.sql.SqlOperator) RexToExpressionVisitor(com.hazelcast.jet.sql.impl.opt.physical.visitor.RexToExpressionVisitor) Expression(com.hazelcast.sql.impl.expression.Expression) Preconditions.checkTrue(com.hazelcast.internal.util.Preconditions.checkTrue) RelTraitSet(org.apache.calcite.plan.RelTraitSet) RelOptCluster(org.apache.calcite.plan.RelOptCluster) FunctionEx(com.hazelcast.function.FunctionEx) TableFunctionScan(org.apache.calcite.rel.core.TableFunctionScan) RelDataType(org.apache.calcite.rel.type.RelDataType) Set(java.util.Set) RelNode(org.apache.calcite.rel.RelNode) RexInputRef(org.apache.calcite.rex.RexInputRef) List(java.util.List) ExpressionEvalContext(com.hazelcast.sql.impl.expression.ExpressionEvalContext) Type(java.lang.reflect.Type) HazelcastSqlOperatorTable(com.hazelcast.jet.sql.impl.validate.HazelcastSqlOperatorTable) SlidingWindowPolicy.tumblingWinPolicy(com.hazelcast.jet.core.SlidingWindowPolicy.tumblingWinPolicy) WindowUtils(com.hazelcast.jet.sql.impl.aggregate.WindowUtils) RexCall(org.apache.calcite.rex.RexCall) HazelcastRelOptCluster(org.apache.calcite.plan.HazelcastRelOptCluster) RexToExpressionVisitor(com.hazelcast.jet.sql.impl.opt.physical.visitor.RexToExpressionVisitor) Expression(com.hazelcast.sql.impl.expression.Expression) QueryParameterMetadata(com.hazelcast.sql.impl.QueryParameterMetadata)

Example 2 with FunctionEx

use of com.hazelcast.function.FunctionEx in project hazelcast by hazelcast.

the class AggregateAbstractPhysicalRule method aggregateOperation.

protected static AggregateOperation<?, JetSqlRow> aggregateOperation(RelDataType inputType, ImmutableBitSet groupSet, List<AggregateCall> aggregateCalls) {
    List<QueryDataType> operandTypes = OptUtils.schema(inputType).getTypes();
    List<SupplierEx<SqlAggregation>> aggregationProviders = new ArrayList<>();
    List<FunctionEx<JetSqlRow, Object>> valueProviders = new ArrayList<>();
    for (Integer groupIndex : groupSet.toList()) {
        aggregationProviders.add(ValueSqlAggregation::new);
        // getMaybeSerialized is safe for ValueAggr because it only passes the value on
        valueProviders.add(new RowGetMaybeSerializedFn(groupIndex));
    }
    for (AggregateCall aggregateCall : aggregateCalls) {
        boolean distinct = aggregateCall.isDistinct();
        List<Integer> aggregateCallArguments = aggregateCall.getArgList();
        SqlKind kind = aggregateCall.getAggregation().getKind();
        switch(kind) {
            case COUNT:
                if (distinct) {
                    int countIndex = aggregateCallArguments.get(0);
                    aggregationProviders.add(new AggregateCountSupplier(true, true));
                    // getMaybeSerialized is safe for COUNT because the aggregation only looks whether it is null or not
                    valueProviders.add(new RowGetMaybeSerializedFn(countIndex));
                } else if (aggregateCallArguments.size() == 1) {
                    int countIndex = aggregateCallArguments.get(0);
                    aggregationProviders.add(new AggregateCountSupplier(true, false));
                    valueProviders.add(new RowGetMaybeSerializedFn(countIndex));
                } else {
                    aggregationProviders.add(new AggregateCountSupplier(false, false));
                    valueProviders.add(NullFunction.INSTANCE);
                }
                break;
            case MIN:
                int minIndex = aggregateCallArguments.get(0);
                aggregationProviders.add(MinSqlAggregation::new);
                valueProviders.add(new RowGetFn(minIndex));
                break;
            case MAX:
                int maxIndex = aggregateCallArguments.get(0);
                aggregationProviders.add(MaxSqlAggregation::new);
                valueProviders.add(new RowGetFn(maxIndex));
                break;
            case SUM:
                int sumIndex = aggregateCallArguments.get(0);
                QueryDataType sumOperandType = operandTypes.get(sumIndex);
                aggregationProviders.add(new AggregateSumSupplier(distinct, sumOperandType));
                valueProviders.add(new RowGetFn(sumIndex));
                break;
            case AVG:
                int avgIndex = aggregateCallArguments.get(0);
                QueryDataType avgOperandType = operandTypes.get(avgIndex);
                aggregationProviders.add(new AggregateAvgSupplier(distinct, avgOperandType));
                valueProviders.add(new RowGetFn(avgIndex));
                break;
            default:
                throw QueryException.error("Unsupported aggregation function: " + kind);
        }
    }
    return AggregateOperation.withCreate(new AggregateCreateSupplier(aggregationProviders)).andAccumulate(new AggregateAccumulateFunction(valueProviders)).andCombine(AggregateCombineFunction.INSTANCE).andExportFinish(AggregateExportFinishFunction.INSTANCE);
}
Also used : MaxSqlAggregation(com.hazelcast.jet.sql.impl.aggregate.MaxSqlAggregation) QueryDataType(com.hazelcast.sql.impl.type.QueryDataType) ArrayList(java.util.ArrayList) SupplierEx(com.hazelcast.function.SupplierEx) SqlKind(org.apache.calcite.sql.SqlKind) ValueSqlAggregation(com.hazelcast.jet.sql.impl.aggregate.ValueSqlAggregation) AggregateCall(org.apache.calcite.rel.core.AggregateCall) MinSqlAggregation(com.hazelcast.jet.sql.impl.aggregate.MinSqlAggregation) FunctionEx(com.hazelcast.function.FunctionEx)

Example 3 with FunctionEx

use of com.hazelcast.function.FunctionEx in project hazelcast by hazelcast.

the class CreateDagVisitor method onSlidingWindowAggregate.

public Vertex onSlidingWindowAggregate(SlidingWindowAggregatePhysicalRel rel) {
    FunctionEx<JetSqlRow, ?> groupKeyFn = rel.groupKeyFn();
    AggregateOperation<?, JetSqlRow> aggregateOperation = rel.aggrOp();
    Expression<?> timestampExpression = rel.timestampExpression();
    ToLongFunctionEx<JetSqlRow> timestampFn = row -> WindowUtils.extractMillis(timestampExpression.eval(row.getRow(), MOCK_EEC));
    SlidingWindowPolicy windowPolicy = rel.windowPolicyProvider().apply(MOCK_EEC);
    KeyedWindowResultFunction<? super Object, ? super JetSqlRow, ?> resultMapping = rel.outputValueMapping();
    if (rel.numStages() == 1) {
        Vertex vertex = dag.newUniqueVertex("Sliding-Window-AggregateByKey", Processors.aggregateToSlidingWindowP(singletonList(groupKeyFn), singletonList(timestampFn), TimestampKind.EVENT, windowPolicy, 0, aggregateOperation, resultMapping));
        connectInput(rel.getInput(), vertex, edge -> edge.distributeTo(localMemberAddress).allToOne(""));
        return vertex;
    } else {
        assert rel.numStages() == 2;
        Vertex vertex1 = dag.newUniqueVertex("Sliding-Window-AccumulateByKey", Processors.accumulateByFrameP(singletonList(groupKeyFn), singletonList(timestampFn), TimestampKind.EVENT, windowPolicy, aggregateOperation));
        Vertex vertex2 = dag.newUniqueVertex("Sliding-Window-CombineByKey", Processors.combineToSlidingWindowP(windowPolicy, aggregateOperation, resultMapping));
        connectInput(rel.getInput(), vertex1, edge -> edge.partitioned(groupKeyFn));
        dag.edge(between(vertex1, vertex2).distributed().partitioned(entryKey()));
        return vertex2;
    }
}
Also used : Address(com.hazelcast.cluster.Address) Traverser(com.hazelcast.jet.Traverser) ExpressionValues(com.hazelcast.jet.sql.impl.opt.ExpressionValues) PlanObjectKey(com.hazelcast.sql.impl.optimizer.PlanObjectKey) Processors.mapP(com.hazelcast.jet.core.processor.Processors.mapP) SourceProcessors.convenientSourceP(com.hazelcast.jet.core.processor.SourceProcessors.convenientSourceP) QueryParameterMetadata(com.hazelcast.sql.impl.QueryParameterMetadata) Collections.singletonList(java.util.Collections.singletonList) BiFunctionEx(com.hazelcast.function.BiFunctionEx) HazelcastTable(com.hazelcast.jet.sql.impl.schema.HazelcastTable) ObjectArrayKey(com.hazelcast.jet.sql.impl.ObjectArrayKey) SlidingWindowPolicy(com.hazelcast.jet.core.SlidingWindowPolicy) SqlConnectorUtil(com.hazelcast.jet.sql.impl.connector.SqlConnectorUtil) AggregateOperation(com.hazelcast.jet.aggregate.AggregateOperation) Functions.entryKey(com.hazelcast.function.Functions.entryKey) SqlConnectorUtil.getJetSqlConnector(com.hazelcast.jet.sql.impl.connector.SqlConnectorUtil.getJetSqlConnector) DAG(com.hazelcast.jet.core.DAG) RootResultConsumerSink.rootResultConsumerSink(com.hazelcast.jet.sql.impl.processors.RootResultConsumerSink.rootResultConsumerSink) ServiceFactories(com.hazelcast.jet.pipeline.ServiceFactories) FunctionEx(com.hazelcast.function.FunctionEx) KeyedWindowResultFunction(com.hazelcast.jet.core.function.KeyedWindowResultFunction) Predicate(java.util.function.Predicate) Collections.emptyList(java.util.Collections.emptyList) Set(java.util.Set) ConsumerEx(com.hazelcast.function.ConsumerEx) IMapSqlConnector(com.hazelcast.jet.sql.impl.connector.map.IMapSqlConnector) ExpressionUtil(com.hazelcast.jet.sql.impl.ExpressionUtil) Processors.filterUsingServiceP(com.hazelcast.jet.core.processor.Processors.filterUsingServiceP) List(java.util.List) ExpressionEvalContext(com.hazelcast.sql.impl.expression.ExpressionEvalContext) Processors.mapUsingServiceP(com.hazelcast.jet.core.processor.Processors.mapUsingServiceP) Table(com.hazelcast.sql.impl.schema.Table) ComparatorEx(com.hazelcast.function.ComparatorEx) QueryDataType(com.hazelcast.sql.impl.type.QueryDataType) Processors(com.hazelcast.jet.core.processor.Processors) Processors.flatMapUsingServiceP(com.hazelcast.jet.core.processor.Processors.flatMapUsingServiceP) TimestampKind(com.hazelcast.jet.core.TimestampKind) Function(java.util.function.Function) JetSqlRow(com.hazelcast.sql.impl.row.JetSqlRow) HashSet(java.util.HashSet) Edge.from(com.hazelcast.jet.core.Edge.from) Edge(com.hazelcast.jet.core.Edge) Expression(com.hazelcast.sql.impl.expression.Expression) ProcessorSupplier(com.hazelcast.jet.core.ProcessorSupplier) VertexWithInputConfig(com.hazelcast.jet.sql.impl.connector.SqlConnector.VertexWithInputConfig) SingleRel(org.apache.calcite.rel.SingleRel) Nullable(javax.annotation.Nullable) JetJoinInfo(com.hazelcast.jet.sql.impl.JetJoinInfo) NodeEngine(com.hazelcast.spi.impl.NodeEngine) ProcessorMetaSupplier(com.hazelcast.jet.core.ProcessorMetaSupplier) RelNode(org.apache.calcite.rel.RelNode) Consumer(java.util.function.Consumer) Vertex(com.hazelcast.jet.core.Vertex) ToLongFunctionEx(com.hazelcast.function.ToLongFunctionEx) SqlHashJoinP(com.hazelcast.jet.sql.impl.processors.SqlHashJoinP) ConstantExpression(com.hazelcast.sql.impl.expression.ConstantExpression) Processors.sortP(com.hazelcast.jet.core.processor.Processors.sortP) DefaultSerializationServiceBuilder(com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder) WindowUtils(com.hazelcast.jet.sql.impl.aggregate.WindowUtils) Edge.between(com.hazelcast.jet.core.Edge.between) Vertex(com.hazelcast.jet.core.Vertex) SlidingWindowPolicy(com.hazelcast.jet.core.SlidingWindowPolicy) JetSqlRow(com.hazelcast.sql.impl.row.JetSqlRow)

Example 4 with FunctionEx

use of com.hazelcast.function.FunctionEx in project hazelcast by hazelcast.

the class JmsSourceBuilder method build.

/**
 * Creates and returns the JMS {@link StreamSource} with the supplied
 * components and the projection function {@code projectionFn}.
 * <p>
 * The given function must be stateless.
 *
 * @param projectionFn the function which creates output object from each
 *                    message
 * @param <T> the type of the items the source emits
 */
@Nonnull
public <T> StreamSource<T> build(@Nonnull FunctionEx<? super Message, ? extends T> projectionFn) {
    String usernameLocal = username;
    String passwordLocal = password;
    String destinationLocal = destinationName;
    ProcessingGuarantee maxGuaranteeLocal = maxGuarantee;
    @SuppressWarnings("UnnecessaryLocalVariable") boolean isTopicLocal = isTopic;
    if (connectionFn == null) {
        connectionFn = factory -> requireNonNull(usernameLocal != null || passwordLocal != null ? factory.createConnection(usernameLocal, passwordLocal) : factory.createConnection());
    }
    if (consumerFn == null) {
        checkNotNull(destinationLocal, "neither consumerFn nor destinationName set");
        consumerFn = session -> session.createConsumer(isTopicLocal ? session.createTopic(destinationLocal) : session.createQueue(destinationLocal));
        if (isTopic) {
            // the user didn't specify a custom consumerFn and we know we're using a non-durable consumer
            // for a topic - there's no point in using any guarantee, see `maxGuarantee`
            maxGuaranteeLocal = ProcessingGuarantee.NONE;
        }
    }
    ProcessingGuarantee maxGuaranteeFinal = maxGuaranteeLocal;
    FunctionEx<? super ConnectionFactory, ? extends Connection> connectionFnLocal = connectionFn;
    @SuppressWarnings("UnnecessaryLocalVariable") SupplierEx<? extends ConnectionFactory> factorySupplierLocal = factorySupplier;
    SupplierEx<? extends Connection> newConnectionFn = () -> connectionFnLocal.apply(factorySupplierLocal.get());
    FunctionEx<? super Session, ? extends MessageConsumer> consumerFnLocal = consumerFn;
    boolean isSharedConsumerLocal = isSharedConsumer;
    FunctionEx<? super Message, ?> messageIdFnLocal = messageIdFn;
    FunctionEx<EventTimePolicy<? super T>, ProcessorMetaSupplier> metaSupplierFactory = policy -> isTopicLocal ? streamJmsTopicP(destinationLocal, isSharedConsumerLocal, maxGuaranteeFinal, policy, newConnectionFn, consumerFnLocal, messageIdFnLocal, projectionFn) : streamJmsQueueP(destinationLocal, maxGuaranteeFinal, policy, newConnectionFn, consumerFnLocal, messageIdFnLocal, projectionFn);
    return Sources.streamFromProcessorWithWatermarks(sourceName(), true, metaSupplierFactory);
}
Also used : ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee) FunctionEx(com.hazelcast.function.FunctionEx) Connection(javax.jms.Connection) Util.checkSerializable(com.hazelcast.jet.impl.util.Util.checkSerializable) ProcessorMetaSupplier(com.hazelcast.jet.core.ProcessorMetaSupplier) EventTimePolicy(com.hazelcast.jet.core.EventTimePolicy) Preconditions.checkNotNull(com.hazelcast.internal.util.Preconditions.checkNotNull) SupplierEx(com.hazelcast.function.SupplierEx) Session(javax.jms.Session) MessageConsumer(javax.jms.MessageConsumer) SourceProcessors.streamJmsTopicP(com.hazelcast.jet.core.processor.SourceProcessors.streamJmsTopicP) Objects.requireNonNull(java.util.Objects.requireNonNull) SourceProcessors.streamJmsQueueP(com.hazelcast.jet.core.processor.SourceProcessors.streamJmsQueueP) ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee) Nonnull(javax.annotation.Nonnull) Message(javax.jms.Message) Nullable(javax.annotation.Nullable) ConnectionFactory(javax.jms.ConnectionFactory) EventTimePolicy(com.hazelcast.jet.core.EventTimePolicy) ProcessorMetaSupplier(com.hazelcast.jet.core.ProcessorMetaSupplier) Nonnull(javax.annotation.Nonnull)

Example 5 with FunctionEx

use of com.hazelcast.function.FunctionEx in project hazelcast by hazelcast.

the class ComputeStageImplBase method attachMapUsingPartitionedService.

@Nonnull
@SuppressWarnings({ "unchecked", "rawtypes" })
<S, K, R, RET> RET attachMapUsingPartitionedService(@Nonnull ServiceFactory<?, S> serviceFactory, @Nonnull FunctionEx<? super T, ? extends K> partitionKeyFn, @Nonnull BiFunctionEx<? super S, ? super T, ? extends R> mapFn) {
    checkSerializable(mapFn, "mapFn");
    checkSerializable(partitionKeyFn, "partitionKeyFn");
    serviceFactory = moveAttachedFilesToPipeline(serviceFactory);
    BiFunctionEx adaptedMapFn = fnAdapter.adaptMapUsingServiceFn(mapFn);
    FunctionEx adaptedPartitionKeyFn = fnAdapter.adaptKeyFn(partitionKeyFn);
    return (RET) attach(mapUsingServicePartitionedTransform(transform, serviceFactory, adaptedMapFn, adaptedPartitionKeyFn), fnAdapter);
}
Also used : BiFunctionEx(com.hazelcast.function.BiFunctionEx) FunctionEx(com.hazelcast.function.FunctionEx) ToLongFunctionEx(com.hazelcast.function.ToLongFunctionEx) BiFunctionEx(com.hazelcast.function.BiFunctionEx) Nonnull(javax.annotation.Nonnull)

Aggregations

FunctionEx (com.hazelcast.function.FunctionEx)44 List (java.util.List)30 Nonnull (javax.annotation.Nonnull)20 DAG (com.hazelcast.jet.core.DAG)18 Test (org.junit.Test)18 Collections.singletonList (java.util.Collections.singletonList)15 Assert.assertEquals (org.junit.Assert.assertEquals)15 Edge (com.hazelcast.jet.core.Edge)14 BiFunctionEx (com.hazelcast.function.BiFunctionEx)13 Function (java.util.function.Function)13 LongAccumulator (com.hazelcast.jet.accumulator.LongAccumulator)12 ArrayList (java.util.ArrayList)12 ToLongFunctionEx (com.hazelcast.function.ToLongFunctionEx)11 Vertex (com.hazelcast.jet.core.Vertex)11 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)11 Entry (java.util.Map.Entry)11 Assert.assertTrue (org.junit.Assert.assertTrue)11 JetException (com.hazelcast.jet.JetException)10 AggregateOperation1 (com.hazelcast.jet.aggregate.AggregateOperation1)10 QuickTest (com.hazelcast.test.annotation.QuickTest)10