You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by florianschmidt1994 <gi...@git.apache.org> on 2018/02/14 10:12:20 UTC

[GitHub] flink pull request #5482: [Flink-8480][DataStream] Add Java API for timeboun...

GitHub user florianschmidt1994 opened a pull request:

    https://github.com/apache/flink/pull/5482

    [Flink-8480][DataStream] Add Java API for timebounded stream join

    ## What is the purpose of the change
    
    * Add a JavaAPI to the DataStream API to join two streams based on user-defined time boundaries
    * Design doc can be found here https://docs.google.com/document/d/16GMH5VM6JJiWj_N0W8y3PtQ1aoJFxsKoOTSYOfqlsRE/edit#heading=h.bgl260hr56g6
    
    ## Brief change log
    * Add option`.between(Time, Time)` to streams that are already joined and have their key selectors `where` and `equalTo` defined
    * Add new inner class `TimeBounded` to `JoinedStreams`, which exposes `process(TimeBoundedJoinFunction)` as well as optional `upperBoundExclusive(boolean)` and `lowerBoundExclusive(boolean)` to the user
    * Add new integration test `TimeboundedJoinITCase`
    * **Depends on [FLINK-8479] to be merged**
    
    Full example usage:
    
    ```java
    streamOne
    	.join(streamTwo)
    	.where(new MyKeySelector())
    	.equalTo(new MyKeySelector())
    	.between(Time.milliseconds(-1), Time.milliseconds(1))
    	.process(new UdfTimeBoundedJoinFunction())
    	.addSink(new ResultSink());
    ```
    
    ## Verifying this change
    This change added tests and can be verified as follows: 
    - Added integration tests in `TimeboundedJoinITCase` that validate parameter translation and execution
    
    ## Does this pull request potentially affect one of the following parts:
    
      - Dependencies (does it add or upgrade a dependency): no
      - The public API, i.e., is any changed class annotated with `@Public(Evolving)`: yes
      - The serializers: no
      - The runtime per-record code paths (performance sensitive): yes
      - Anything that affects deployment or recovery: no
      - The S3 file system connector: no
    
    ## Documentation
    
      - Does this pull request introduce a new feature? yes
      - If yes, how is the feature documented? JavaDocs


You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/florianschmidt1994/flink flink-8480-timebounded-join-java-api

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/flink/pull/5482.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #5482
    
----
commit 34451540116d8bdd284fd01016a4cc74d8564d37
Author: Florian Schmidt <fl...@...>
Date:   2018-01-18T14:47:14Z

    [FLINK-8479] Implement TimeBoundedStreamJoinOperator
    
    This operator is the basis for performing an inner join on two
    streams using a time criteria defined as a lower and upper bound

commit fe65b1ead0511b0df5d640c728f5ce9e273d7ed5
Author: Florian Schmidt <fl...@...>
Date:   2018-02-13T14:48:40Z

    [FLINK-8480][DataStream] Add java api for timebounded stream joins
    
    This commit adds a java implementation for timebounded stream joins.
    The usage looks roughly like the following:
    
    ```java
    streamOne
    	.join(streamTwo)
    	.where(new Tuple2KeyExtractor())
    	.equalTo(new Tuple2KeyExtractor())
    	.between(Time.milliseconds(0), Time.milliseconds(1))
    	.process(new CombineToStringJoinFunction())
    	.addSink(new ResultSink());
    ```
    
    This change adds the functionality in JoinedStreams.java and adds
    integration tests in TimeboundedJoinITCase.java

----


---

[GitHub] flink issue #5482: [FLINK-8480][DataStream] Add Java API for timebounded str...

Posted by florianschmidt1994 <gi...@git.apache.org>.
Github user florianschmidt1994 commented on the issue:

    https://github.com/apache/flink/pull/5482
  
    Thanks for your comments @bowenli86 and sorry for the delay! I added some comments and some stuff I'll be addressing right away


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by bowenli86 <gi...@git.apache.org>.
Github user bowenli86 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r172303671
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/TimeBoundedStreamJoinOperator.java ---
    @@ -0,0 +1,480 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *    http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.streaming.api.functions;
    +
    +import org.apache.flink.annotation.Internal;
    +import org.apache.flink.annotation.VisibleForTesting;
    +import org.apache.flink.api.common.state.MapState;
    +import org.apache.flink.api.common.state.MapStateDescriptor;
    +import org.apache.flink.api.common.typeutils.TypeSerializer;
    +import org.apache.flink.api.common.typeutils.base.BooleanSerializer;
    +import org.apache.flink.api.common.typeutils.base.ListSerializer;
    +import org.apache.flink.api.common.typeutils.base.LongSerializer;
    +import org.apache.flink.api.java.tuple.Tuple2;
    +import org.apache.flink.api.java.tuple.Tuple3;
    +import org.apache.flink.api.java.typeutils.runtime.TupleSerializer;
    +import org.apache.flink.runtime.state.StateInitializationContext;
    +import org.apache.flink.runtime.state.VoidNamespace;
    +import org.apache.flink.runtime.state.VoidNamespaceSerializer;
    +import org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator;
    +import org.apache.flink.streaming.api.operators.InternalTimer;
    +import org.apache.flink.streaming.api.operators.InternalTimerService;
    +import org.apache.flink.streaming.api.operators.TimestampedCollector;
    +import org.apache.flink.streaming.api.operators.Triggerable;
    +import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
    +import org.apache.flink.streaming.api.watermark.Watermark;
    +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
    +import org.apache.flink.util.OutputTag;
    +import org.apache.flink.util.Preconditions;
    +
    +import java.util.ArrayList;
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +/**
    + * A TwoInputStreamOperator to execute time-bounded stream inner joins.
    + *
    + * <p>By using a configurable lower and upper bound this operator will emit exactly those pairs
    + * (T1, T2) where t2.ts ∈ [T1.ts + lowerBound, T1.ts + upperBound]. Both the lower and the
    + * upper bound can be configured to be either inclusive or exclusive.
    --- End diff --
    
    bound**s**


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by florianschmidt1994 <gi...@git.apache.org>.
Github user florianschmidt1994 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r183706512
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/TimeBoundedStreamJoinOperator.java ---
    @@ -0,0 +1,480 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *    http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.streaming.api.functions;
    +
    +import org.apache.flink.annotation.Internal;
    +import org.apache.flink.annotation.VisibleForTesting;
    +import org.apache.flink.api.common.state.MapState;
    +import org.apache.flink.api.common.state.MapStateDescriptor;
    +import org.apache.flink.api.common.typeutils.TypeSerializer;
    +import org.apache.flink.api.common.typeutils.base.BooleanSerializer;
    +import org.apache.flink.api.common.typeutils.base.ListSerializer;
    +import org.apache.flink.api.common.typeutils.base.LongSerializer;
    +import org.apache.flink.api.java.tuple.Tuple2;
    +import org.apache.flink.api.java.tuple.Tuple3;
    +import org.apache.flink.api.java.typeutils.runtime.TupleSerializer;
    +import org.apache.flink.runtime.state.StateInitializationContext;
    +import org.apache.flink.runtime.state.VoidNamespace;
    +import org.apache.flink.runtime.state.VoidNamespaceSerializer;
    +import org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator;
    +import org.apache.flink.streaming.api.operators.InternalTimer;
    +import org.apache.flink.streaming.api.operators.InternalTimerService;
    +import org.apache.flink.streaming.api.operators.TimestampedCollector;
    +import org.apache.flink.streaming.api.operators.Triggerable;
    +import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
    +import org.apache.flink.streaming.api.watermark.Watermark;
    +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
    +import org.apache.flink.util.OutputTag;
    +import org.apache.flink.util.Preconditions;
    +
    +import java.util.ArrayList;
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +/**
    + * A TwoInputStreamOperator to execute time-bounded stream inner joins.
    + *
    + * <p>By using a configurable lower and upper bound this operator will emit exactly those pairs
    + * (T1, T2) where t2.ts ∈ [T1.ts + lowerBound, T1.ts + upperBound]. Both the lower and the
    + * upper bound can be configured to be either inclusive or exclusive.
    --- End diff --
    
    You mean the spelling? I can address this in the PR of the TimeBoundedStreamJoinOperator


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by florianschmidt1994 <gi...@git.apache.org>.
Github user florianschmidt1994 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r183712409
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/TimeBoundedStreamJoinOperator.java ---
    @@ -0,0 +1,480 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *    http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.streaming.api.functions;
    +
    +import org.apache.flink.annotation.Internal;
    +import org.apache.flink.annotation.VisibleForTesting;
    +import org.apache.flink.api.common.state.MapState;
    +import org.apache.flink.api.common.state.MapStateDescriptor;
    +import org.apache.flink.api.common.typeutils.TypeSerializer;
    +import org.apache.flink.api.common.typeutils.base.BooleanSerializer;
    +import org.apache.flink.api.common.typeutils.base.ListSerializer;
    +import org.apache.flink.api.common.typeutils.base.LongSerializer;
    +import org.apache.flink.api.java.tuple.Tuple2;
    +import org.apache.flink.api.java.tuple.Tuple3;
    +import org.apache.flink.api.java.typeutils.runtime.TupleSerializer;
    +import org.apache.flink.runtime.state.StateInitializationContext;
    +import org.apache.flink.runtime.state.VoidNamespace;
    +import org.apache.flink.runtime.state.VoidNamespaceSerializer;
    +import org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator;
    +import org.apache.flink.streaming.api.operators.InternalTimer;
    +import org.apache.flink.streaming.api.operators.InternalTimerService;
    +import org.apache.flink.streaming.api.operators.TimestampedCollector;
    +import org.apache.flink.streaming.api.operators.Triggerable;
    +import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
    +import org.apache.flink.streaming.api.watermark.Watermark;
    +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
    +import org.apache.flink.util.OutputTag;
    +import org.apache.flink.util.Preconditions;
    +
    +import java.util.ArrayList;
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +/**
    + * A TwoInputStreamOperator to execute time-bounded stream inner joins.
    + *
    + * <p>By using a configurable lower and upper bound this operator will emit exactly those pairs
    + * (T1, T2) where t2.ts ∈ [T1.ts + lowerBound, T1.ts + upperBound]. Both the lower and the
    + * upper bound can be configured to be either inclusive or exclusive.
    + *
    + * <p>As soon as elements are joined they are passed to a user-defined {@link TimeBoundedJoinFunction},
    + * as a {@link Tuple2}, with f0 being the left element and f1 being the right element
    + *
    + * <p>The basic idea of this implementation is as follows: Whenever we receive an element at
    + * {@link #processElement1(StreamRecord)} (a.k.a. the left side), we add it to the left buffer.
    + * We then check the right buffer to see whether there are any elements that can be joined. If
    + * there are, they are joined and passed to a user-defined {@link TimeBoundedJoinFunction}.
    + * The same happens the other way around when receiving an element on the right side.
    + *
    + * <p>In some cases the watermark needs to be delayed. This for example can happen if
    + * if t2.ts ∈ [t1.ts + 1, t1.ts + 2] and elements from t1 arrive earlier than elements from t2 and
    + * therefore get added to the left buffer. When an element now arrives on the right side, the
    + * watermark might have already progressed. The right element now gets joined with an
    + * older element from the left side, where the timestamp of the left element is lower than the
    + * current watermark, which would make this element late. This can be avoided by holding back the
    + * watermarks.
    + *
    + * <p>The left and right buffers are cleared from unused values periodically
    + * (triggered by watermarks) in order not to grow infinitely.
    + *
    + *
    + * @param <T1> The type of the elements in the left stream
    + * @param <T2> The type of the elements in the right stream
    + * @param <OUT> The output type created by the user-defined function
    + */
    +@Internal
    +public class TimeBoundedStreamJoinOperator<K, T1, T2, OUT>
    +	extends AbstractUdfStreamOperator<OUT, TimeBoundedJoinFunction<T1, T2, OUT>>
    +	implements TwoInputStreamOperator<T1, T2, OUT>, Triggerable<K, VoidNamespace> {
    +
    +	private static final String LEFT_BUFFER = "LEFT_BUFFER";
    +	private static final String RIGHT_BUFFER = "RIGHT_BUFFER";
    +	private static final String CLEANUP_TIMER_NAME = "CLEANUP_TIMER";
    +
    +	private final long lowerBound;
    +	private final long upperBound;
    +
    +	private final long inverseLowerBound;
    +	private final long inverseUpperBound;
    +
    +	private final boolean lowerBoundInclusive;
    +	private final boolean upperBoundInclusive;
    +
    +	private final TypeSerializer<T1> leftTypeSerializer;
    +	private final TypeSerializer<T2> rightTypeSerializer;
    +
    +	private final long bucketGranularity;
    +	private final long watermarkDelay;
    +
    +	private long lastWatermark = Long.MIN_VALUE;
    +
    +	private transient MapState<Long, List<Tuple3<T1, Long, Boolean>>> leftBuffer;
    +	private transient MapState<Long, List<Tuple3<T2, Long, Boolean>>> rightBuffer;
    +
    +	private transient TimestampedCollector<OUT> collector;
    +	private transient ContextImpl context;
    +
    +	private transient InternalTimerService<VoidNamespace> internalTimerService;
    +
    +	/**
    +	 * Creates a new TimeBoundedStreamJoinOperator.
    +	 *
    +	 * @param lowerBound          The lower bound for evaluating if elements should be joined
    +	 * @param upperBound          The upper bound for evaluating if elements should be joined
    +	 * @param lowerBoundInclusive Whether or not to include elements where the timestamp matches
    +	 *                            the lower bound
    +	 * @param upperBoundInclusive Whether or not to include elements where the timestamp matches
    +	 *                            the upper bound
    +	 * @param udf                 A user-defined {@link TimeBoundedJoinFunction} that gets called
    +	 *                            whenever two elements of T1 and T2 are joined
    +	 */
    +	public TimeBoundedStreamJoinOperator(
    +			long lowerBound,
    +			long upperBound,
    +			boolean lowerBoundInclusive,
    +			boolean upperBoundInclusive,
    +			long bucketGranularity,
    +			TypeSerializer<T1> leftTypeSerializer,
    +			TypeSerializer<T2> rightTypeSerializer,
    +			TimeBoundedJoinFunction<T1, T2, OUT> udf) {
    +
    +		super(Preconditions.checkNotNull(udf));
    +
    +		Preconditions.checkArgument(lowerBound <= upperBound,
    +			"lowerBound <= upperBound must be fulfilled");
    +		Preconditions.checkArgument(bucketGranularity > 0, "bucket size must be greater than zero");
    +
    +		this.lowerBound = lowerBound;
    +		this.upperBound = upperBound;
    +
    +		this.inverseLowerBound = -1 * upperBound;
    +		this.inverseUpperBound = -1 * lowerBound;
    +
    +		this.lowerBoundInclusive = lowerBoundInclusive;
    +		this.upperBoundInclusive = upperBoundInclusive;
    +		this.leftTypeSerializer = Preconditions.checkNotNull(leftTypeSerializer);
    +		this.rightTypeSerializer = Preconditions.checkNotNull(rightTypeSerializer);
    +
    +		this.bucketGranularity = bucketGranularity;
    +		this.watermarkDelay = (upperBound < 0) ? 0 : upperBound;
    +	}
    +
    +	@Override
    +	public void open() throws Exception {
    +		super.open();
    +		collector = new TimestampedCollector<>(output);
    +		context = new ContextImpl(userFunction);
    +		internalTimerService =
    +			getInternalTimerService(CLEANUP_TIMER_NAME, VoidNamespaceSerializer.INSTANCE, this);
    +	}
    +
    +	@Override
    +	public void initializeState(StateInitializationContext context) throws Exception {
    +		super.initializeState(context);
    +
    +		@SuppressWarnings("unchecked")
    +		Class<Tuple3<T1, Long, Boolean>> leftTypedTuple =
    +			(Class<Tuple3<T1, Long, Boolean>>) (Class<?>) Tuple3.class;
    +
    +		TupleSerializer<Tuple3<T1, Long, Boolean>> leftTupleSerializer = new TupleSerializer<>(
    +			leftTypedTuple,
    +			new TypeSerializer[]{
    +				leftTypeSerializer,
    +				LongSerializer.INSTANCE,
    +				BooleanSerializer.INSTANCE
    +			}
    +		);
    +
    +		@SuppressWarnings("unchecked")
    +		Class<Tuple3<T2, Long, Boolean>> rightTypedTuple =
    +			(Class<Tuple3<T2, Long, Boolean>>) (Class<?>) Tuple3.class;
    +
    +		TupleSerializer<Tuple3<T2, Long, Boolean>> rightTupleSerializer = new TupleSerializer<>(
    +			rightTypedTuple,
    +			new TypeSerializer[]{
    +				rightTypeSerializer,
    +				LongSerializer.INSTANCE,
    +				BooleanSerializer.INSTANCE
    +			}
    +		);
    +
    +		this.leftBuffer = getRuntimeContext().getMapState(new MapStateDescriptor<>(
    +			LEFT_BUFFER,
    +			LongSerializer.INSTANCE,
    +			new ListSerializer<>(leftTupleSerializer)
    +		));
    +
    +		this.rightBuffer = getRuntimeContext().getMapState(new MapStateDescriptor<>(
    +			RIGHT_BUFFER,
    +			LongSerializer.INSTANCE,
    +			new ListSerializer<>(rightTupleSerializer)
    +		));
    +	}
    +
    +	/**
    +	 * Process a {@link StreamRecord} from the left stream. Whenever an {@link StreamRecord}
    +	 * arrives at the left stream, it will get added to the left buffer. Possible join candidates
    +	 * for that element will be looked up from the right buffer and if the pair lies within the
    +	 * user defined boundaries, it gets collected.
    +	 *
    +	 * @param record An incoming record to be joined
    +	 * @throws Exception Can throw an Exception during state access
    +	 */
    +	@Override
    +	public void processElement1(StreamRecord<T1> record) throws Exception {
    +
    +		T1 leftValue = record.getValue();
    +		long leftTs = record.getTimestamp();
    +
    +		long joinLowerBound = leftTs + lowerBound;
    +		long joinUpperBound = leftTs + upperBound;
    +
    +		if (leftTs == Long.MIN_VALUE) {
    +			throw new RuntimeException("Time-bounded stream joins need to have timestamps " +
    +				"assigned to elements, but current element has timestamp Long.MIN_VALUE");
    +		}
    +
    +		if (dataIsLate(leftTs)) {
    +			return;
    +		}
    +
    +		addToLeftBuffer(leftValue, leftTs);
    +
    +		for (Map.Entry<Long, List<Tuple3<T2, Long, Boolean>>> entry : rightBuffer.entries()) {
    +			long bucketStart = entry.getKey();
    +			long bucketEnd = bucketStart + bucketGranularity;
    +
    +			if (!(bucketEnd >= joinLowerBound && bucketStart <= joinUpperBound)) {
    +				// skip buckets that are out of bounds
    +				continue;
    +			}
    +
    +			List<Tuple3<T2, Long, Boolean>> fromBucket = entry.getValue();
    +
    +			// check for each element in current bucket if it should be joined
    +			for (Tuple3<T2, Long, Boolean> tuple : fromBucket) {
    +				if (shouldBeJoined(leftTs, tuple.f1)) {
    +
    +					// collect joined tuple with left timestamp
    +					collect(leftValue, tuple.f0, leftTs, tuple.f1);
    +				}
    +			}
    +		}
    +
    +		registerCleanupTimer();
    +
    +	}
    +
    +	private void registerCleanupTimer() {
    +		if (this.lastWatermark == Long.MIN_VALUE) {
    +			return;
    +		}
    +
    +		long triggerTime = this.lastWatermark + 1;
    +		internalTimerService.registerEventTimeTimer(VoidNamespace.INSTANCE, triggerTime);
    +	}
    +
    +	/**
    +	 * Process a {@link StreamRecord} from the right stream. Whenever a {@link StreamRecord}
    +	 * arrives at the right stream, it will get added to the right buffer. Possible join candidates
    +	 * for that element will be looked up from the left buffer and if the pair lies within the user
    +	 * defined boundaries, it gets collected.
    +	 *
    +	 * @param record An incoming record to be joined
    +	 * @throws Exception Can throw an exception during state access
    +	 */
    +	@Override
    +	public void processElement2(StreamRecord<T2> record) throws Exception {
    +
    +		long rightTs = record.getTimestamp();
    +		T2 rightElem = record.getValue();
    +
    +		long joinLowerBound = rightTs + inverseLowerBound;
    +		long joinUpperBound = rightTs + inverseUpperBound;
    +
    +		addToRightBuffer(rightElem, rightTs);
    +
    +		if (rightTs == Long.MIN_VALUE) {
    +			throw new RuntimeException("Time-bounded stream joins need to have timestamps " +
    +				"assigned to elements, but current element has timestamp Long.MIN_VALUE");
    +		}
    +
    +		if (dataIsLate(rightTs)) {
    +			return;
    +		}
    +
    +		for (Map.Entry<Long, List<Tuple3<T1, Long, Boolean>>> entry : leftBuffer.entries()) {
    +			long bucketStart = entry.getKey();
    +			long bucketEnd = bucketStart + bucketGranularity;
    +
    +			if (!(bucketEnd >= joinLowerBound && bucketStart <= joinUpperBound)) {
    +				// skip buckets that are out of bounds
    +				continue;
    +			}
    +
    +			for (Tuple3<T1, Long, Boolean> tuple : entry.getValue()) {
    +				if (shouldBeJoined(tuple.f1, rightTs)) {
    +
    +					// collect joined tuple with left timestamp
    +					collect(tuple.f0, rightElem, tuple.f1, rightTs);
    +				}
    +			}
    +		}
    +
    +		registerCleanupTimer();
    +	}
    +
    +	private boolean dataIsLate(long rightTs) {
    +		return this.lastWatermark != Long.MIN_VALUE && rightTs < lastWatermark - watermarkDelay;
    +	}
    +
    +	@Override
    +	public void processWatermark(Watermark mark) throws Exception {
    +
    +		// We can not clean our state here directly because we are not in a keyed context. Instead
    +		// we set a field containing the last watermark that we have seen, and for every element in
    +		// processElement1(...) / processElement2(...) we register a timer with time: watermark + 1
    +		// This watermark + 1 will then trigger the onEventTime(...) method for the next watermark,
    +		// where we are in a keyed context again, which we can use to clean up our state.
    +		this.lastWatermark = mark.getTimestamp();
    +
    +		if (timeServiceManager != null) {
    +			timeServiceManager.advanceWatermark(mark);
    +		}
    +
    +		// emit the watermark with the calculated delay, so we don't produce late data
    +		output.emitWatermark(new Watermark(this.lastWatermark - watermarkDelay));
    +	}
    +
    +	private void collect(T1 left, T2 right, long leftTs, long rightTs) throws Exception {
    +		collector.setAbsoluteTimestamp(leftTs);
    +		context.leftTs = leftTs;
    +		context.rightTs = rightTs;
    +		userFunction.processElement(left, right, context, this.collector);
    +	}
    +
    +	private void removeFromLhsUntil(long maxCleanup) throws Exception {
    +
    +		Iterator<Map.Entry<Long, List<Tuple3<T1, Long, Boolean>>>> iterator = leftBuffer.iterator();
    +		while (iterator.hasNext()) {
    +			Map.Entry<Long, List<Tuple3<T1, Long, Boolean>>> next = iterator.next();
    +			if (next.getKey() + bucketGranularity <= maxCleanup) {
    +				iterator.remove();
    --- End diff --
    
    With the effectively single-threaded execution model of the operators I don't think there should be any problems here, as far as I understand. The only other thread accessing the state should be the checkpointing one, and I'd assume that this happens in a safe manner. 
    I had a quick chat with @kl0u and he confirmed this


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for Interval...

Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:

    https://github.com/apache/flink/pull/5482


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by bowenli86 <gi...@git.apache.org>.
Github user bowenli86 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r172306197
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/TimeBoundedStreamJoinOperator.java ---
    @@ -0,0 +1,480 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *    http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.streaming.api.functions;
    +
    +import org.apache.flink.annotation.Internal;
    +import org.apache.flink.annotation.VisibleForTesting;
    +import org.apache.flink.api.common.state.MapState;
    +import org.apache.flink.api.common.state.MapStateDescriptor;
    +import org.apache.flink.api.common.typeutils.TypeSerializer;
    +import org.apache.flink.api.common.typeutils.base.BooleanSerializer;
    +import org.apache.flink.api.common.typeutils.base.ListSerializer;
    +import org.apache.flink.api.common.typeutils.base.LongSerializer;
    +import org.apache.flink.api.java.tuple.Tuple2;
    +import org.apache.flink.api.java.tuple.Tuple3;
    +import org.apache.flink.api.java.typeutils.runtime.TupleSerializer;
    +import org.apache.flink.runtime.state.StateInitializationContext;
    +import org.apache.flink.runtime.state.VoidNamespace;
    +import org.apache.flink.runtime.state.VoidNamespaceSerializer;
    +import org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator;
    +import org.apache.flink.streaming.api.operators.InternalTimer;
    +import org.apache.flink.streaming.api.operators.InternalTimerService;
    +import org.apache.flink.streaming.api.operators.TimestampedCollector;
    +import org.apache.flink.streaming.api.operators.Triggerable;
    +import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
    +import org.apache.flink.streaming.api.watermark.Watermark;
    +import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
    +import org.apache.flink.util.OutputTag;
    +import org.apache.flink.util.Preconditions;
    +
    +import java.util.ArrayList;
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +/**
    + * A TwoInputStreamOperator to execute time-bounded stream inner joins.
    + *
    + * <p>By using a configurable lower and upper bound this operator will emit exactly those pairs
    + * (T1, T2) where t2.ts ∈ [T1.ts + lowerBound, T1.ts + upperBound]. Both the lower and the
    + * upper bound can be configured to be either inclusive or exclusive.
    + *
    + * <p>As soon as elements are joined they are passed to a user-defined {@link TimeBoundedJoinFunction},
    + * as a {@link Tuple2}, with f0 being the left element and f1 being the right element
    + *
    + * <p>The basic idea of this implementation is as follows: Whenever we receive an element at
    + * {@link #processElement1(StreamRecord)} (a.k.a. the left side), we add it to the left buffer.
    + * We then check the right buffer to see whether there are any elements that can be joined. If
    + * there are, they are joined and passed to a user-defined {@link TimeBoundedJoinFunction}.
    + * The same happens the other way around when receiving an element on the right side.
    + *
    + * <p>In some cases the watermark needs to be delayed. This for example can happen if
    + * if t2.ts ∈ [t1.ts + 1, t1.ts + 2] and elements from t1 arrive earlier than elements from t2 and
    + * therefore get added to the left buffer. When an element now arrives on the right side, the
    + * watermark might have already progressed. The right element now gets joined with an
    + * older element from the left side, where the timestamp of the left element is lower than the
    + * current watermark, which would make this element late. This can be avoided by holding back the
    + * watermarks.
    + *
    + * <p>The left and right buffers are cleared from unused values periodically
    + * (triggered by watermarks) in order not to grow infinitely.
    + *
    + *
    + * @param <T1> The type of the elements in the left stream
    + * @param <T2> The type of the elements in the right stream
    + * @param <OUT> The output type created by the user-defined function
    + */
    +@Internal
    +public class TimeBoundedStreamJoinOperator<K, T1, T2, OUT>
    +	extends AbstractUdfStreamOperator<OUT, TimeBoundedJoinFunction<T1, T2, OUT>>
    +	implements TwoInputStreamOperator<T1, T2, OUT>, Triggerable<K, VoidNamespace> {
    +
    +	private static final String LEFT_BUFFER = "LEFT_BUFFER";
    +	private static final String RIGHT_BUFFER = "RIGHT_BUFFER";
    +	private static final String CLEANUP_TIMER_NAME = "CLEANUP_TIMER";
    +
    +	private final long lowerBound;
    +	private final long upperBound;
    +
    +	private final long inverseLowerBound;
    +	private final long inverseUpperBound;
    +
    +	private final boolean lowerBoundInclusive;
    +	private final boolean upperBoundInclusive;
    +
    +	private final TypeSerializer<T1> leftTypeSerializer;
    +	private final TypeSerializer<T2> rightTypeSerializer;
    +
    +	private final long bucketGranularity;
    +	private final long watermarkDelay;
    +
    +	private long lastWatermark = Long.MIN_VALUE;
    +
    +	private transient MapState<Long, List<Tuple3<T1, Long, Boolean>>> leftBuffer;
    +	private transient MapState<Long, List<Tuple3<T2, Long, Boolean>>> rightBuffer;
    +
    +	private transient TimestampedCollector<OUT> collector;
    +	private transient ContextImpl context;
    +
    +	private transient InternalTimerService<VoidNamespace> internalTimerService;
    +
    +	/**
    +	 * Creates a new TimeBoundedStreamJoinOperator.
    +	 *
    +	 * @param lowerBound          The lower bound for evaluating if elements should be joined
    +	 * @param upperBound          The upper bound for evaluating if elements should be joined
    +	 * @param lowerBoundInclusive Whether or not to include elements where the timestamp matches
    +	 *                            the lower bound
    +	 * @param upperBoundInclusive Whether or not to include elements where the timestamp matches
    +	 *                            the upper bound
    +	 * @param udf                 A user-defined {@link TimeBoundedJoinFunction} that gets called
    +	 *                            whenever two elements of T1 and T2 are joined
    +	 */
    +	public TimeBoundedStreamJoinOperator(
    +			long lowerBound,
    +			long upperBound,
    +			boolean lowerBoundInclusive,
    +			boolean upperBoundInclusive,
    +			long bucketGranularity,
    +			TypeSerializer<T1> leftTypeSerializer,
    +			TypeSerializer<T2> rightTypeSerializer,
    +			TimeBoundedJoinFunction<T1, T2, OUT> udf) {
    +
    +		super(Preconditions.checkNotNull(udf));
    +
    +		Preconditions.checkArgument(lowerBound <= upperBound,
    +			"lowerBound <= upperBound must be fulfilled");
    +		Preconditions.checkArgument(bucketGranularity > 0, "bucket size must be greater than zero");
    +
    +		this.lowerBound = lowerBound;
    +		this.upperBound = upperBound;
    +
    +		this.inverseLowerBound = -1 * upperBound;
    +		this.inverseUpperBound = -1 * lowerBound;
    +
    +		this.lowerBoundInclusive = lowerBoundInclusive;
    +		this.upperBoundInclusive = upperBoundInclusive;
    +		this.leftTypeSerializer = Preconditions.checkNotNull(leftTypeSerializer);
    +		this.rightTypeSerializer = Preconditions.checkNotNull(rightTypeSerializer);
    +
    +		this.bucketGranularity = bucketGranularity;
    +		this.watermarkDelay = (upperBound < 0) ? 0 : upperBound;
    +	}
    +
    +	@Override
    +	public void open() throws Exception {
    +		super.open();
    +		collector = new TimestampedCollector<>(output);
    +		context = new ContextImpl(userFunction);
    +		internalTimerService =
    +			getInternalTimerService(CLEANUP_TIMER_NAME, VoidNamespaceSerializer.INSTANCE, this);
    +	}
    +
    +	@Override
    +	public void initializeState(StateInitializationContext context) throws Exception {
    +		super.initializeState(context);
    +
    +		@SuppressWarnings("unchecked")
    +		Class<Tuple3<T1, Long, Boolean>> leftTypedTuple =
    +			(Class<Tuple3<T1, Long, Boolean>>) (Class<?>) Tuple3.class;
    +
    +		TupleSerializer<Tuple3<T1, Long, Boolean>> leftTupleSerializer = new TupleSerializer<>(
    +			leftTypedTuple,
    +			new TypeSerializer[]{
    +				leftTypeSerializer,
    +				LongSerializer.INSTANCE,
    +				BooleanSerializer.INSTANCE
    +			}
    +		);
    +
    +		@SuppressWarnings("unchecked")
    +		Class<Tuple3<T2, Long, Boolean>> rightTypedTuple =
    +			(Class<Tuple3<T2, Long, Boolean>>) (Class<?>) Tuple3.class;
    +
    +		TupleSerializer<Tuple3<T2, Long, Boolean>> rightTupleSerializer = new TupleSerializer<>(
    +			rightTypedTuple,
    +			new TypeSerializer[]{
    +				rightTypeSerializer,
    +				LongSerializer.INSTANCE,
    +				BooleanSerializer.INSTANCE
    +			}
    +		);
    +
    +		this.leftBuffer = getRuntimeContext().getMapState(new MapStateDescriptor<>(
    +			LEFT_BUFFER,
    +			LongSerializer.INSTANCE,
    +			new ListSerializer<>(leftTupleSerializer)
    +		));
    +
    +		this.rightBuffer = getRuntimeContext().getMapState(new MapStateDescriptor<>(
    +			RIGHT_BUFFER,
    +			LongSerializer.INSTANCE,
    +			new ListSerializer<>(rightTupleSerializer)
    +		));
    +	}
    +
    +	/**
    +	 * Process a {@link StreamRecord} from the left stream. Whenever an {@link StreamRecord}
    +	 * arrives at the left stream, it will get added to the left buffer. Possible join candidates
    +	 * for that element will be looked up from the right buffer and if the pair lies within the
    +	 * user defined boundaries, it gets collected.
    +	 *
    +	 * @param record An incoming record to be joined
    +	 * @throws Exception Can throw an Exception during state access
    +	 */
    +	@Override
    +	public void processElement1(StreamRecord<T1> record) throws Exception {
    +
    +		T1 leftValue = record.getValue();
    +		long leftTs = record.getTimestamp();
    +
    +		long joinLowerBound = leftTs + lowerBound;
    +		long joinUpperBound = leftTs + upperBound;
    +
    +		if (leftTs == Long.MIN_VALUE) {
    +			throw new RuntimeException("Time-bounded stream joins need to have timestamps " +
    +				"assigned to elements, but current element has timestamp Long.MIN_VALUE");
    +		}
    +
    +		if (dataIsLate(leftTs)) {
    +			return;
    +		}
    +
    +		addToLeftBuffer(leftValue, leftTs);
    +
    +		for (Map.Entry<Long, List<Tuple3<T2, Long, Boolean>>> entry : rightBuffer.entries()) {
    +			long bucketStart = entry.getKey();
    +			long bucketEnd = bucketStart + bucketGranularity;
    +
    +			if (!(bucketEnd >= joinLowerBound && bucketStart <= joinUpperBound)) {
    +				// skip buckets that are out of bounds
    +				continue;
    +			}
    +
    +			List<Tuple3<T2, Long, Boolean>> fromBucket = entry.getValue();
    +
    +			// check for each element in current bucket if it should be joined
    +			for (Tuple3<T2, Long, Boolean> tuple : fromBucket) {
    +				if (shouldBeJoined(leftTs, tuple.f1)) {
    +
    +					// collect joined tuple with left timestamp
    +					collect(leftValue, tuple.f0, leftTs, tuple.f1);
    +				}
    +			}
    +		}
    +
    +		registerCleanupTimer();
    +
    +	}
    +
    +	private void registerCleanupTimer() {
    +		if (this.lastWatermark == Long.MIN_VALUE) {
    +			return;
    +		}
    +
    +		long triggerTime = this.lastWatermark + 1;
    +		internalTimerService.registerEventTimeTimer(VoidNamespace.INSTANCE, triggerTime);
    +	}
    +
    +	/**
    +	 * Process a {@link StreamRecord} from the right stream. Whenever a {@link StreamRecord}
    +	 * arrives at the right stream, it will get added to the right buffer. Possible join candidates
    +	 * for that element will be looked up from the left buffer and if the pair lies within the user
    +	 * defined boundaries, it gets collected.
    +	 *
    +	 * @param record An incoming record to be joined
    +	 * @throws Exception Can throw an exception during state access
    +	 */
    +	@Override
    +	public void processElement2(StreamRecord<T2> record) throws Exception {
    +
    +		long rightTs = record.getTimestamp();
    +		T2 rightElem = record.getValue();
    +
    +		long joinLowerBound = rightTs + inverseLowerBound;
    +		long joinUpperBound = rightTs + inverseUpperBound;
    +
    +		addToRightBuffer(rightElem, rightTs);
    +
    +		if (rightTs == Long.MIN_VALUE) {
    +			throw new RuntimeException("Time-bounded stream joins need to have timestamps " +
    +				"assigned to elements, but current element has timestamp Long.MIN_VALUE");
    +		}
    +
    +		if (dataIsLate(rightTs)) {
    +			return;
    +		}
    +
    +		for (Map.Entry<Long, List<Tuple3<T1, Long, Boolean>>> entry : leftBuffer.entries()) {
    +			long bucketStart = entry.getKey();
    +			long bucketEnd = bucketStart + bucketGranularity;
    +
    +			if (!(bucketEnd >= joinLowerBound && bucketStart <= joinUpperBound)) {
    +				// skip buckets that are out of bounds
    +				continue;
    +			}
    +
    +			for (Tuple3<T1, Long, Boolean> tuple : entry.getValue()) {
    +				if (shouldBeJoined(tuple.f1, rightTs)) {
    +
    +					// collect joined tuple with left timestamp
    +					collect(tuple.f0, rightElem, tuple.f1, rightTs);
    +				}
    +			}
    +		}
    +
    +		registerCleanupTimer();
    +	}
    +
    +	private boolean dataIsLate(long rightTs) {
    +		return this.lastWatermark != Long.MIN_VALUE && rightTs < lastWatermark - watermarkDelay;
    +	}
    +
    +	@Override
    +	public void processWatermark(Watermark mark) throws Exception {
    +
    +		// We can not clean our state here directly because we are not in a keyed context. Instead
    +		// we set a field containing the last watermark that we have seen, and for every element in
    +		// processElement1(...) / processElement2(...) we register a timer with time: watermark + 1
    +		// This watermark + 1 will then trigger the onEventTime(...) method for the next watermark,
    +		// where we are in a keyed context again, which we can use to clean up our state.
    +		this.lastWatermark = mark.getTimestamp();
    +
    +		if (timeServiceManager != null) {
    +			timeServiceManager.advanceWatermark(mark);
    +		}
    +
    +		// emit the watermark with the calculated delay, so we don't produce late data
    +		output.emitWatermark(new Watermark(this.lastWatermark - watermarkDelay));
    +	}
    +
    +	private void collect(T1 left, T2 right, long leftTs, long rightTs) throws Exception {
    +		collector.setAbsoluteTimestamp(leftTs);
    +		context.leftTs = leftTs;
    +		context.rightTs = rightTs;
    +		userFunction.processElement(left, right, context, this.collector);
    +	}
    +
    +	private void removeFromLhsUntil(long maxCleanup) throws Exception {
    +
    +		Iterator<Map.Entry<Long, List<Tuple3<T1, Long, Boolean>>>> iterator = leftBuffer.iterator();
    +		while (iterator.hasNext()) {
    +			Map.Entry<Long, List<Tuple3<T1, Long, Boolean>>> next = iterator.next();
    +			if (next.getKey() + bucketGranularity <= maxCleanup) {
    +				iterator.remove();
    --- End diff --
    
    I'm not a big fan of the troublesome `iterator.remove()`. Will there be concurrent access to `left/rightBuffer` while removing elements from them?


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by florianschmidt1994 <gi...@git.apache.org>.
Github user florianschmidt1994 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r183705882
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java ---
    @@ -137,6 +158,151 @@ public EqualTo equalTo(KeySelector<T2, KEY> keySelector)  {
     			public <W extends Window> WithWindow<T1, T2, KEY, W> window(WindowAssigner<? super TaggedUnion<T1, T2>, W> assigner) {
     				return new WithWindow<>(input1, input2, keySelector1, keySelector2, keyType, assigner, null, null);
     			}
    +
    +			/**
    +			 * Specifies the time boundaries over which the join operation works, so that
    +			 * <pre>leftElement.timestamp + lowerBound <= rightElement.timestamp <= leftElement.timestamp + upperBound</pre>
    +			 * By default both the lower and the upper bound are inclusive. This can be configured
    +			 * with {@link TimeBounded#lowerBoundExclusive(boolean)} and
    +			 * {@link TimeBounded#upperBoundExclusive(boolean)}
    +			 *
    +			 * @param lowerBound The lower bound. Needs to be smaller than or equal to the upperBound
    +			 * @param upperBound The upper bound. Needs to be bigger than or equal to the lowerBound
    +			 */
    +			public TimeBounded<T1, T2, KEY> between(Time lowerBound, Time upperBound) {
    +
    +				TimeCharacteristic timeCharacteristic =
    +					input1.getExecutionEnvironment().getStreamTimeCharacteristic();
    +
    +				if (timeCharacteristic != TimeCharacteristic.EventTime) {
    +					throw new RuntimeException("Time-bounded stream joins are only supported in event time");
    +				}
    +
    +				checkNotNull(lowerBound, "A lower bound needs to be provided for a time-bounded join");
    +				checkNotNull(upperBound, "An upper bound needs to be provided for a time-bounded join");
    +				return new TimeBounded<>(
    +					input1,
    +					input2,
    +					lowerBound.toMilliseconds(),
    +					upperBound.toMilliseconds(),
    +					true,
    +					true,
    +					keySelector1,
    +					keySelector2
    +				);
    +			}
    +		}
    +	}
    +
    +	/**
    +	 * Joined streams that have keys for both sides as well as the time boundaries over which
    +	 * elements should be joined defined.
    +	 *
    +	 * @param <IN1> Input type of elements from the first stream
    +	 * @param <IN2> Input type of elements from the second stream
    +	 * @param <KEY> The type of the key
    +	 */
    +	public static class TimeBounded<IN1, IN2, KEY> {
    +
    +		private static final String TIMEBOUNDED_JOIN_FUNC_NAME = "TimeBoundedJoin";
    +
    +		private final DataStream<IN1> left;
    +		private final DataStream<IN2> right;
    +
    +		private final long lowerBound;
    +		private final long upperBound;
    +
    +		private final KeySelector<IN1, KEY> keySelector1;
    +		private final KeySelector<IN2, KEY> keySelector2;
    +
    +		private boolean lowerBoundInclusive;
    +		private boolean upperBoundInclusive;
    +
    +		public TimeBounded(
    +			DataStream<IN1> left,
    +			DataStream<IN2> right,
    +			long lowerBound,
    +			long upperBound,
    +			boolean lowerBoundInclusive,
    +			boolean upperBoundInclusive,
    +			KeySelector<IN1, KEY> keySelector1,
    +			KeySelector<IN2, KEY> keySelector2) {
    +
    +			this.left = Preconditions.checkNotNull(left);
    +			this.right = Preconditions.checkNotNull(right);
    +
    +			this.lowerBound = lowerBound;
    +			this.upperBound = upperBound;
    +
    +			this.lowerBoundInclusive = lowerBoundInclusive;
    +			this.upperBoundInclusive = upperBoundInclusive;
    +
    +			this.keySelector1 = Preconditions.checkNotNull(keySelector1);
    +			this.keySelector2 = Preconditions.checkNotNull(keySelector2);
    +		}
    +
    +		/**
    +		 * Configure whether the upper bound should be considered exclusive or inclusive.
    +		 */
    +		public TimeBounded<IN1, IN2, KEY> upperBoundExclusive(boolean exclusive) {
    +			this.upperBoundInclusive = !exclusive;
    +			return this;
    +		}
    +
    +		/**
    +		 * Configure whether the lower bound should be considered exclusive or inclusive.
    +		 */
    +		public TimeBounded<IN1, IN2, KEY> lowerBoundExclusive(boolean exclusive) {
    +			this.lowerBoundInclusive = !exclusive;
    +			return this;
    +		}
    +
    +		/**
    +		 * Completes the join operation with the user function that is executed for each joined pair
    +		 * of elements.
    +		 * @param udf The user-defined function
    +		 * @param <OUT> The output type
    +		 * @return Returns a DataStream
    +		 */
    +		public <OUT> DataStream<OUT> process(TimeBoundedJoinFunction<IN1, IN2, OUT> udf) {
    +
    +			ConnectedStreams<IN1, IN2> connected = left.connect(right);
    +
    +			udf = left.getExecutionEnvironment().clean(udf);
    +
    +			TypeInformation<OUT> resultType = TypeExtractor.getBinaryOperatorReturnType(
    +				udf,
    +				TimeBoundedJoinFunction.class,    // TimeBoundedJoinFunction<IN1, IN2, OUT>
    +				0,                                //						  0    1    2
    +				1,
    +				2,
    +				new int[]{0},                   // lambda input 1 type arg indices
    +				new int[]{1},                   // lambda input 1 type arg indices
    +				TypeExtractor.NO_INDEX,         // output arg indices
    +				left.getType(),                 // input 1 type information
    +				right.getType(),                // input 1 type information
    +				TIMEBOUNDED_JOIN_FUNC_NAME,
    +				false
    +			);
    +
    +			long bucketGranularity = Time.seconds(1).toMilliseconds();
    --- End diff --
    
    Yes, this should actually be exposed either through the API or config file (or both?). I'll give this one some thought as well and come back


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by kl0u <gi...@git.apache.org>.
Github user kl0u commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r183745456
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java ---
    @@ -137,6 +158,151 @@ public EqualTo equalTo(KeySelector<T2, KEY> keySelector)  {
     			public <W extends Window> WithWindow<T1, T2, KEY, W> window(WindowAssigner<? super TaggedUnion<T1, T2>, W> assigner) {
     				return new WithWindow<>(input1, input2, keySelector1, keySelector2, keyType, assigner, null, null);
     			}
    +
    +			/**
    +			 * Specifies the time boundaries over which the join operation works, so that
    +			 * <pre>leftElement.timestamp + lowerBound <= rightElement.timestamp <= leftElement.timestamp + upperBound</pre>
    +			 * By default both the lower and the upper bound are inclusive. This can be configured
    +			 * with {@link TimeBounded#lowerBoundExclusive(boolean)} and
    +			 * {@link TimeBounded#upperBoundExclusive(boolean)}
    +			 *
    +			 * @param lowerBound The lower bound. Needs to be smaller than or equal to the upperBound
    +			 * @param upperBound The upper bound. Needs to be bigger than or equal to the lowerBound
    +			 */
    +			public TimeBounded<T1, T2, KEY> between(Time lowerBound, Time upperBound) {
    +
    +				TimeCharacteristic timeCharacteristic =
    +					input1.getExecutionEnvironment().getStreamTimeCharacteristic();
    +
    +				if (timeCharacteristic != TimeCharacteristic.EventTime) {
    +					throw new RuntimeException("Time-bounded stream joins are only supported in event time");
    +				}
    +
    +				checkNotNull(lowerBound, "A lower bound needs to be provided for a time-bounded join");
    +				checkNotNull(upperBound, "An upper bound needs to be provided for a time-bounded join");
    +				return new TimeBounded<>(
    +					input1,
    +					input2,
    +					lowerBound.toMilliseconds(),
    +					upperBound.toMilliseconds(),
    +					true,
    +					true,
    +					keySelector1,
    +					keySelector2
    +				);
    +			}
    +		}
    +	}
    +
    +	/**
    +	 * Joined streams that have keys for both sides as well as the time boundaries over which
    +	 * elements should be joined defined.
    +	 *
    +	 * @param <IN1> Input type of elements from the first stream
    +	 * @param <IN2> Input type of elements from the second stream
    +	 * @param <KEY> The type of the key
    +	 */
    +	public static class TimeBounded<IN1, IN2, KEY> {
    +
    +		private static final String TIMEBOUNDED_JOIN_FUNC_NAME = "TimeBoundedJoin";
    +
    +		private final DataStream<IN1> left;
    +		private final DataStream<IN2> right;
    +
    +		private final long lowerBound;
    +		private final long upperBound;
    +
    +		private final KeySelector<IN1, KEY> keySelector1;
    +		private final KeySelector<IN2, KEY> keySelector2;
    +
    +		private boolean lowerBoundInclusive;
    +		private boolean upperBoundInclusive;
    +
    +		public TimeBounded(
    +			DataStream<IN1> left,
    +			DataStream<IN2> right,
    +			long lowerBound,
    +			long upperBound,
    +			boolean lowerBoundInclusive,
    +			boolean upperBoundInclusive,
    +			KeySelector<IN1, KEY> keySelector1,
    +			KeySelector<IN2, KEY> keySelector2) {
    +
    +			this.left = Preconditions.checkNotNull(left);
    +			this.right = Preconditions.checkNotNull(right);
    +
    +			this.lowerBound = lowerBound;
    +			this.upperBound = upperBound;
    +
    +			this.lowerBoundInclusive = lowerBoundInclusive;
    +			this.upperBoundInclusive = upperBoundInclusive;
    +
    +			this.keySelector1 = Preconditions.checkNotNull(keySelector1);
    +			this.keySelector2 = Preconditions.checkNotNull(keySelector2);
    +		}
    +
    +		/**
    +		 * Configure whether the upper bound should be considered exclusive or inclusive.
    +		 */
    +		public TimeBounded<IN1, IN2, KEY> upperBoundExclusive(boolean exclusive) {
    +			this.upperBoundInclusive = !exclusive;
    +			return this;
    +		}
    +
    +		/**
    +		 * Configure whether the lower bound should be considered exclusive or inclusive.
    +		 */
    +		public TimeBounded<IN1, IN2, KEY> lowerBoundExclusive(boolean exclusive) {
    +			this.lowerBoundInclusive = !exclusive;
    +			return this;
    +		}
    +
    +		/**
    +		 * Completes the join operation with the user function that is executed for each joined pair
    +		 * of elements.
    +		 * @param udf The user-defined function
    +		 * @param <OUT> The output type
    +		 * @return Returns a DataStream
    +		 */
    +		public <OUT> DataStream<OUT> process(TimeBoundedJoinFunction<IN1, IN2, OUT> udf) {
    +
    +			ConnectedStreams<IN1, IN2> connected = left.connect(right);
    +
    +			udf = left.getExecutionEnvironment().clean(udf);
    +
    +			TypeInformation<OUT> resultType = TypeExtractor.getBinaryOperatorReturnType(
    +				udf,
    +				TimeBoundedJoinFunction.class,    // TimeBoundedJoinFunction<IN1, IN2, OUT>
    +				0,                                //						  0    1    2
    +				1,
    +				2,
    +				new int[]{0},                   // lambda input 1 type arg indices
    +				new int[]{1},                   // lambda input 1 type arg indices
    +				TypeExtractor.NO_INDEX,         // output arg indices
    +				left.getType(),                 // input 1 type information
    +				right.getType(),                // input 1 type information
    +				TIMEBOUNDED_JOIN_FUNC_NAME,
    +				false
    +			);
    +
    +			long bucketGranularity = Time.seconds(1).toMilliseconds();
    --- End diff --
    
    I would be up for not exposing this parameter to the users. This is an internal thing that we use in the current implementation. In the future, we may not even use buckets for the joins.
    
    In addition, exposing it means exposing internal parameters to the user, which normally is not a good idea. We can always add this parameter if we see that it makes a difference in practice. Removing it if we change our mind in the future is always more tricky.


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by bowenli86 <gi...@git.apache.org>.
Github user bowenli86 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r172302147
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java ---
    @@ -137,6 +158,151 @@ public EqualTo equalTo(KeySelector<T2, KEY> keySelector)  {
     			public <W extends Window> WithWindow<T1, T2, KEY, W> window(WindowAssigner<? super TaggedUnion<T1, T2>, W> assigner) {
     				return new WithWindow<>(input1, input2, keySelector1, keySelector2, keyType, assigner, null, null);
     			}
    +
    +			/**
    +			 * Specifies the time boundaries over which the join operation works, so that
    +			 * <pre>leftElement.timestamp + lowerBound <= rightElement.timestamp <= leftElement.timestamp + upperBound</pre>
    +			 * By default both the lower and the upper bound are inclusive. This can be configured
    +			 * with {@link TimeBounded#lowerBoundExclusive(boolean)} and
    +			 * {@link TimeBounded#upperBoundExclusive(boolean)}
    +			 *
    +			 * @param lowerBound The lower bound. Needs to be smaller than or equal to the upperBound
    +			 * @param upperBound The upper bound. Needs to be bigger than or equal to the lowerBound
    +			 */
    +			public TimeBounded<T1, T2, KEY> between(Time lowerBound, Time upperBound) {
    +
    +				TimeCharacteristic timeCharacteristic =
    +					input1.getExecutionEnvironment().getStreamTimeCharacteristic();
    +
    +				if (timeCharacteristic != TimeCharacteristic.EventTime) {
    +					throw new RuntimeException("Time-bounded stream joins are only supported in event time");
    --- End diff --
    
    should use `IllegalStateException`. or even better, shall we create a Flink specific exception?


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by bowenli86 <gi...@git.apache.org>.
Github user bowenli86 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r172302583
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java ---
    @@ -137,6 +158,151 @@ public EqualTo equalTo(KeySelector<T2, KEY> keySelector)  {
     			public <W extends Window> WithWindow<T1, T2, KEY, W> window(WindowAssigner<? super TaggedUnion<T1, T2>, W> assigner) {
     				return new WithWindow<>(input1, input2, keySelector1, keySelector2, keyType, assigner, null, null);
     			}
    +
    +			/**
    +			 * Specifies the time boundaries over which the join operation works, so that
    +			 * <pre>leftElement.timestamp + lowerBound <= rightElement.timestamp <= leftElement.timestamp + upperBound</pre>
    +			 * By default both the lower and the upper bound are inclusive. This can be configured
    +			 * with {@link TimeBounded#lowerBoundExclusive(boolean)} and
    +			 * {@link TimeBounded#upperBoundExclusive(boolean)}
    +			 *
    +			 * @param lowerBound The lower bound. Needs to be smaller than or equal to the upperBound
    +			 * @param upperBound The upper bound. Needs to be bigger than or equal to the lowerBound
    +			 */
    +			public TimeBounded<T1, T2, KEY> between(Time lowerBound, Time upperBound) {
    +
    +				TimeCharacteristic timeCharacteristic =
    +					input1.getExecutionEnvironment().getStreamTimeCharacteristic();
    +
    +				if (timeCharacteristic != TimeCharacteristic.EventTime) {
    +					throw new RuntimeException("Time-bounded stream joins are only supported in event time");
    +				}
    +
    +				checkNotNull(lowerBound, "A lower bound needs to be provided for a time-bounded join");
    +				checkNotNull(upperBound, "An upper bound needs to be provided for a time-bounded join");
    +				return new TimeBounded<>(
    +					input1,
    +					input2,
    +					lowerBound.toMilliseconds(),
    +					upperBound.toMilliseconds(),
    +					true,
    +					true,
    +					keySelector1,
    +					keySelector2
    +				);
    +			}
    +		}
    +	}
    +
    +	/**
    +	 * Joined streams that have keys for both sides as well as the time boundaries over which
    +	 * elements should be joined defined.
    +	 *
    +	 * @param <IN1> Input type of elements from the first stream
    +	 * @param <IN2> Input type of elements from the second stream
    +	 * @param <KEY> The type of the key
    +	 */
    +	public static class TimeBounded<IN1, IN2, KEY> {
    +
    +		private static final String TIMEBOUNDED_JOIN_FUNC_NAME = "TimeBoundedJoin";
    --- End diff --
    
    hmm... this might be not very relevant, but I'd prefer a single config class that holds all function's names, rather than having them scattered all over the code base. 


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by florianschmidt1994 <gi...@git.apache.org>.
Github user florianschmidt1994 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r183727245
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java ---
    @@ -137,6 +158,151 @@ public EqualTo equalTo(KeySelector<T2, KEY> keySelector)  {
     			public <W extends Window> WithWindow<T1, T2, KEY, W> window(WindowAssigner<? super TaggedUnion<T1, T2>, W> assigner) {
     				return new WithWindow<>(input1, input2, keySelector1, keySelector2, keyType, assigner, null, null);
     			}
    +
    +			/**
    +			 * Specifies the time boundaries over which the join operation works, so that
    +			 * <pre>leftElement.timestamp + lowerBound <= rightElement.timestamp <= leftElement.timestamp + upperBound</pre>
    +			 * By default both the lower and the upper bound are inclusive. This can be configured
    +			 * with {@link TimeBounded#lowerBoundExclusive(boolean)} and
    +			 * {@link TimeBounded#upperBoundExclusive(boolean)}
    +			 *
    +			 * @param lowerBound The lower bound. Needs to be smaller than or equal to the upperBound
    +			 * @param upperBound The upper bound. Needs to be bigger than or equal to the lowerBound
    +			 */
    +			public TimeBounded<T1, T2, KEY> between(Time lowerBound, Time upperBound) {
    +
    +				TimeCharacteristic timeCharacteristic =
    +					input1.getExecutionEnvironment().getStreamTimeCharacteristic();
    +
    +				if (timeCharacteristic != TimeCharacteristic.EventTime) {
    +					throw new RuntimeException("Time-bounded stream joins are only supported in event time");
    +				}
    +
    +				checkNotNull(lowerBound, "A lower bound needs to be provided for a time-bounded join");
    +				checkNotNull(upperBound, "An upper bound needs to be provided for a time-bounded join");
    +				return new TimeBounded<>(
    +					input1,
    +					input2,
    +					lowerBound.toMilliseconds(),
    +					upperBound.toMilliseconds(),
    +					true,
    +					true,
    +					keySelector1,
    +					keySelector2
    +				);
    +			}
    +		}
    +	}
    +
    +	/**
    +	 * Joined streams that have keys for both sides as well as the time boundaries over which
    +	 * elements should be joined defined.
    +	 *
    +	 * @param <IN1> Input type of elements from the first stream
    +	 * @param <IN2> Input type of elements from the second stream
    +	 * @param <KEY> The type of the key
    +	 */
    +	public static class TimeBounded<IN1, IN2, KEY> {
    +
    +		private static final String TIMEBOUNDED_JOIN_FUNC_NAME = "TimeBoundedJoin";
    +
    +		private final DataStream<IN1> left;
    +		private final DataStream<IN2> right;
    +
    +		private final long lowerBound;
    +		private final long upperBound;
    +
    +		private final KeySelector<IN1, KEY> keySelector1;
    +		private final KeySelector<IN2, KEY> keySelector2;
    +
    +		private boolean lowerBoundInclusive;
    +		private boolean upperBoundInclusive;
    +
    +		public TimeBounded(
    +			DataStream<IN1> left,
    +			DataStream<IN2> right,
    +			long lowerBound,
    +			long upperBound,
    +			boolean lowerBoundInclusive,
    +			boolean upperBoundInclusive,
    +			KeySelector<IN1, KEY> keySelector1,
    +			KeySelector<IN2, KEY> keySelector2) {
    +
    +			this.left = Preconditions.checkNotNull(left);
    +			this.right = Preconditions.checkNotNull(right);
    +
    +			this.lowerBound = lowerBound;
    +			this.upperBound = upperBound;
    +
    +			this.lowerBoundInclusive = lowerBoundInclusive;
    +			this.upperBoundInclusive = upperBoundInclusive;
    +
    +			this.keySelector1 = Preconditions.checkNotNull(keySelector1);
    +			this.keySelector2 = Preconditions.checkNotNull(keySelector2);
    +		}
    +
    +		/**
    +		 * Configure whether the upper bound should be considered exclusive or inclusive.
    +		 */
    +		public TimeBounded<IN1, IN2, KEY> upperBoundExclusive(boolean exclusive) {
    +			this.upperBoundInclusive = !exclusive;
    +			return this;
    +		}
    +
    +		/**
    +		 * Configure whether the lower bound should be considered exclusive or inclusive.
    +		 */
    +		public TimeBounded<IN1, IN2, KEY> lowerBoundExclusive(boolean exclusive) {
    +			this.lowerBoundInclusive = !exclusive;
    +			return this;
    +		}
    +
    +		/**
    +		 * Completes the join operation with the user function that is executed for each joined pair
    +		 * of elements.
    +		 * @param udf The user-defined function
    +		 * @param <OUT> The output type
    +		 * @return Returns a DataStream
    +		 */
    +		public <OUT> DataStream<OUT> process(TimeBoundedJoinFunction<IN1, IN2, OUT> udf) {
    +
    +			ConnectedStreams<IN1, IN2> connected = left.connect(right);
    +
    +			udf = left.getExecutionEnvironment().clean(udf);
    +
    +			TypeInformation<OUT> resultType = TypeExtractor.getBinaryOperatorReturnType(
    +				udf,
    +				TimeBoundedJoinFunction.class,    // TimeBoundedJoinFunction<IN1, IN2, OUT>
    +				0,                                //						  0    1    2
    +				1,
    +				2,
    +				new int[]{0},                   // lambda input 1 type arg indices
    +				new int[]{1},                   // lambda input 1 type arg indices
    +				TypeExtractor.NO_INDEX,         // output arg indices
    +				left.getType(),                 // input 1 type information
    +				right.getType(),                // input 1 type information
    +				TIMEBOUNDED_JOIN_FUNC_NAME,
    +				false
    +			);
    +
    +			long bucketGranularity = Time.seconds(1).toMilliseconds();
    --- End diff --
    
    So I built a POC which supports setting it like this
    ```java
    streamOne
      .join(streamTwo)
      .where(new Tuple2KeyExtractor())
      .equalTo(new Tuple2KeyExtractor())
      .between(Time.milliseconds(0), Time.milliseconds(2))
      .withBucketGranularity(Time.hours(1)) // this one here
      .process(new CombineToStringJoinFunction())
      .addSink(new ResultSink());
    ```
    but I'm really not sure about this. To me it feels like the wrong level of abstraction at that point. Maybe @kl0u or @aljoscha have some ideas on where this would fit best? Also putting it in the `flink-config.yaml` feels a little bit too low level


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by florianschmidt1994 <gi...@git.apache.org>.
Github user florianschmidt1994 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r183704705
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java ---
    @@ -137,6 +158,151 @@ public EqualTo equalTo(KeySelector<T2, KEY> keySelector)  {
     			public <W extends Window> WithWindow<T1, T2, KEY, W> window(WindowAssigner<? super TaggedUnion<T1, T2>, W> assigner) {
     				return new WithWindow<>(input1, input2, keySelector1, keySelector2, keyType, assigner, null, null);
     			}
    +
    +			/**
    +			 * Specifies the time boundaries over which the join operation works, so that
    +			 * <pre>leftElement.timestamp + lowerBound <= rightElement.timestamp <= leftElement.timestamp + upperBound</pre>
    +			 * By default both the lower and the upper bound are inclusive. This can be configured
    +			 * with {@link TimeBounded#lowerBoundExclusive(boolean)} and
    +			 * {@link TimeBounded#upperBoundExclusive(boolean)}
    +			 *
    +			 * @param lowerBound The lower bound. Needs to be smaller than or equal to the upperBound
    +			 * @param upperBound The upper bound. Needs to be bigger than or equal to the lowerBound
    +			 */
    +			public TimeBounded<T1, T2, KEY> between(Time lowerBound, Time upperBound) {
    +
    +				TimeCharacteristic timeCharacteristic =
    +					input1.getExecutionEnvironment().getStreamTimeCharacteristic();
    +
    +				if (timeCharacteristic != TimeCharacteristic.EventTime) {
    +					throw new RuntimeException("Time-bounded stream joins are only supported in event time");
    +				}
    +
    +				checkNotNull(lowerBound, "A lower bound needs to be provided for a time-bounded join");
    +				checkNotNull(upperBound, "An upper bound needs to be provided for a time-bounded join");
    +				return new TimeBounded<>(
    +					input1,
    +					input2,
    +					lowerBound.toMilliseconds(),
    +					upperBound.toMilliseconds(),
    +					true,
    +					true,
    +					keySelector1,
    +					keySelector2
    +				);
    +			}
    +		}
    +	}
    +
    +	/**
    +	 * Joined streams that have keys for both sides as well as the time boundaries over which
    +	 * elements should be joined defined.
    +	 *
    +	 * @param <IN1> Input type of elements from the first stream
    +	 * @param <IN2> Input type of elements from the second stream
    +	 * @param <KEY> The type of the key
    +	 */
    +	public static class TimeBounded<IN1, IN2, KEY> {
    +
    +		private static final String TIMEBOUNDED_JOIN_FUNC_NAME = "TimeBoundedJoin";
    --- End diff --
    
    Looks like there is only one other case in the datastream package where we have a `static final ...` as a constant, and it's inlined there as well. I'd propose to keep it here for the time and rethink a config class if we see more cases coming up


---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by florianschmidt1994 <gi...@git.apache.org>.
Github user florianschmidt1994 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r183703916
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java ---
    @@ -137,6 +158,151 @@ public EqualTo equalTo(KeySelector<T2, KEY> keySelector)  {
     			public <W extends Window> WithWindow<T1, T2, KEY, W> window(WindowAssigner<? super TaggedUnion<T1, T2>, W> assigner) {
     				return new WithWindow<>(input1, input2, keySelector1, keySelector2, keyType, assigner, null, null);
     			}
    +
    +			/**
    +			 * Specifies the time boundaries over which the join operation works, so that
    +			 * <pre>leftElement.timestamp + lowerBound <= rightElement.timestamp <= leftElement.timestamp + upperBound</pre>
    +			 * By default both the lower and the upper bound are inclusive. This can be configured
    +			 * with {@link TimeBounded#lowerBoundExclusive(boolean)} and
    +			 * {@link TimeBounded#upperBoundExclusive(boolean)}
    +			 *
    +			 * @param lowerBound The lower bound. Needs to be smaller than or equal to the upperBound
    +			 * @param upperBound The upper bound. Needs to be bigger than or equal to the lowerBound
    +			 */
    +			public TimeBounded<T1, T2, KEY> between(Time lowerBound, Time upperBound) {
    +
    +				TimeCharacteristic timeCharacteristic =
    +					input1.getExecutionEnvironment().getStreamTimeCharacteristic();
    +
    +				if (timeCharacteristic != TimeCharacteristic.EventTime) {
    +					throw new RuntimeException("Time-bounded stream joins are only supported in event time");
    --- End diff --
    
    I'm not sure about the `IllegalStateException`. The description of it says 
    >Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.
    
    But I'm not opposed to the idea of creating a custom exception for all cases where an operation is not supported with the current time characteristic. I'll see if I can think of something 



---

[GitHub] flink pull request #5482: [FLINK-8480][DataStream] Add Java API for timeboun...

Posted by bowenli86 <gi...@git.apache.org>.
Github user bowenli86 commented on a diff in the pull request:

    https://github.com/apache/flink/pull/5482#discussion_r172303424
  
    --- Diff: flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/JoinedStreams.java ---
    @@ -137,6 +158,151 @@ public EqualTo equalTo(KeySelector<T2, KEY> keySelector)  {
     			public <W extends Window> WithWindow<T1, T2, KEY, W> window(WindowAssigner<? super TaggedUnion<T1, T2>, W> assigner) {
     				return new WithWindow<>(input1, input2, keySelector1, keySelector2, keyType, assigner, null, null);
     			}
    +
    +			/**
    +			 * Specifies the time boundaries over which the join operation works, so that
    +			 * <pre>leftElement.timestamp + lowerBound <= rightElement.timestamp <= leftElement.timestamp + upperBound</pre>
    +			 * By default both the lower and the upper bound are inclusive. This can be configured
    +			 * with {@link TimeBounded#lowerBoundExclusive(boolean)} and
    +			 * {@link TimeBounded#upperBoundExclusive(boolean)}
    +			 *
    +			 * @param lowerBound The lower bound. Needs to be smaller than or equal to the upperBound
    +			 * @param upperBound The upper bound. Needs to be bigger than or equal to the lowerBound
    +			 */
    +			public TimeBounded<T1, T2, KEY> between(Time lowerBound, Time upperBound) {
    +
    +				TimeCharacteristic timeCharacteristic =
    +					input1.getExecutionEnvironment().getStreamTimeCharacteristic();
    +
    +				if (timeCharacteristic != TimeCharacteristic.EventTime) {
    +					throw new RuntimeException("Time-bounded stream joins are only supported in event time");
    +				}
    +
    +				checkNotNull(lowerBound, "A lower bound needs to be provided for a time-bounded join");
    +				checkNotNull(upperBound, "An upper bound needs to be provided for a time-bounded join");
    +				return new TimeBounded<>(
    +					input1,
    +					input2,
    +					lowerBound.toMilliseconds(),
    +					upperBound.toMilliseconds(),
    +					true,
    +					true,
    +					keySelector1,
    +					keySelector2
    +				);
    +			}
    +		}
    +	}
    +
    +	/**
    +	 * Joined streams that have keys for both sides as well as the time boundaries over which
    +	 * elements should be joined defined.
    +	 *
    +	 * @param <IN1> Input type of elements from the first stream
    +	 * @param <IN2> Input type of elements from the second stream
    +	 * @param <KEY> The type of the key
    +	 */
    +	public static class TimeBounded<IN1, IN2, KEY> {
    +
    +		private static final String TIMEBOUNDED_JOIN_FUNC_NAME = "TimeBoundedJoin";
    +
    +		private final DataStream<IN1> left;
    +		private final DataStream<IN2> right;
    +
    +		private final long lowerBound;
    +		private final long upperBound;
    +
    +		private final KeySelector<IN1, KEY> keySelector1;
    +		private final KeySelector<IN2, KEY> keySelector2;
    +
    +		private boolean lowerBoundInclusive;
    +		private boolean upperBoundInclusive;
    +
    +		public TimeBounded(
    +			DataStream<IN1> left,
    +			DataStream<IN2> right,
    +			long lowerBound,
    +			long upperBound,
    +			boolean lowerBoundInclusive,
    +			boolean upperBoundInclusive,
    +			KeySelector<IN1, KEY> keySelector1,
    +			KeySelector<IN2, KEY> keySelector2) {
    +
    +			this.left = Preconditions.checkNotNull(left);
    +			this.right = Preconditions.checkNotNull(right);
    +
    +			this.lowerBound = lowerBound;
    +			this.upperBound = upperBound;
    +
    +			this.lowerBoundInclusive = lowerBoundInclusive;
    +			this.upperBoundInclusive = upperBoundInclusive;
    +
    +			this.keySelector1 = Preconditions.checkNotNull(keySelector1);
    +			this.keySelector2 = Preconditions.checkNotNull(keySelector2);
    +		}
    +
    +		/**
    +		 * Configure whether the upper bound should be considered exclusive or inclusive.
    +		 */
    +		public TimeBounded<IN1, IN2, KEY> upperBoundExclusive(boolean exclusive) {
    +			this.upperBoundInclusive = !exclusive;
    +			return this;
    +		}
    +
    +		/**
    +		 * Configure whether the lower bound should be considered exclusive or inclusive.
    +		 */
    +		public TimeBounded<IN1, IN2, KEY> lowerBoundExclusive(boolean exclusive) {
    +			this.lowerBoundInclusive = !exclusive;
    +			return this;
    +		}
    +
    +		/**
    +		 * Completes the join operation with the user function that is executed for each joined pair
    +		 * of elements.
    +		 * @param udf The user-defined function
    +		 * @param <OUT> The output type
    +		 * @return Returns a DataStream
    +		 */
    +		public <OUT> DataStream<OUT> process(TimeBoundedJoinFunction<IN1, IN2, OUT> udf) {
    +
    +			ConnectedStreams<IN1, IN2> connected = left.connect(right);
    +
    +			udf = left.getExecutionEnvironment().clean(udf);
    +
    +			TypeInformation<OUT> resultType = TypeExtractor.getBinaryOperatorReturnType(
    +				udf,
    +				TimeBoundedJoinFunction.class,    // TimeBoundedJoinFunction<IN1, IN2, OUT>
    +				0,                                //						  0    1    2
    +				1,
    +				2,
    +				new int[]{0},                   // lambda input 1 type arg indices
    +				new int[]{1},                   // lambda input 1 type arg indices
    +				TypeExtractor.NO_INDEX,         // output arg indices
    +				left.getType(),                 // input 1 type information
    +				right.getType(),                // input 1 type information
    +				TIMEBOUNDED_JOIN_FUNC_NAME,
    +				false
    +			);
    +
    +			long bucketGranularity = Time.seconds(1).toMilliseconds();
    --- End diff --
    
    does the granularity need to be documented?


---