You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by fh...@apache.org on 2015/12/21 18:44:05 UTC
[2/8] flink git commit: [FLINK-7] Add range partitioning with
automatic sampling of key distribution
[FLINK-7] Add range partitioning with automatic sampling of key distribution
This closes #1255
Project: http://git-wip-us.apache.org/repos/asf/flink/repo
Commit: http://git-wip-us.apache.org/repos/asf/flink/commit/f5957ce3
Tree: http://git-wip-us.apache.org/repos/asf/flink/tree/f5957ce3
Diff: http://git-wip-us.apache.org/repos/asf/flink/diff/f5957ce3
Branch: refs/heads/master
Commit: f5957ce3b7d87d89052f0328e569b74ec8aaa3e0
Parents: aec6ded
Author: chengxiang li <ch...@intel.com>
Authored: Thu Oct 29 10:33:45 2015 +0800
Committer: Fabian Hueske <fh...@apache.org>
Committed: Mon Dec 21 16:43:32 2015 +0100
----------------------------------------------------------------------
docs/apis/dataset_transformations.md | 37 ++-
docs/apis/programming_guide.md | 26 +-
.../ExecutionPlanAfterExecutionTest.java | 33 ++-
.../distributions/CommonRangeBoundaries.java | 77 ++++++
.../common/distributions/DataDistribution.java | 3 +-
.../common/distributions/RangeBoundaries.java | 36 +++
.../java/org/apache/flink/api/java/DataSet.java | 55 +++-
.../api/java/operators/PartitionOperator.java | 12 +-
.../org/apache/flink/optimizer/Optimizer.java | 5 +-
.../flink/optimizer/dag/PartitionNode.java | 11 +-
.../operators/AbstractJoinDescriptor.java | 6 +-
.../optimizer/operators/CoGroupDescriptor.java | 6 +-
.../GroupReduceWithCombineProperties.java | 3 +
.../apache/flink/optimizer/plan/Channel.java | 4 +
.../plantranslate/JobGraphGenerator.java | 3 +-
.../traversals/RangePartitionRewriter.java | 229 ++++++++++++++++
.../org/apache/flink/optimizer/util/Utils.java | 43 +++
.../optimizer/java/PartitionOperatorTest.java | 122 ++++++++-
.../operators/shipping/OutputEmitter.java | 101 +++++++-
.../runtime/operators/udf/AssignRangeIndex.java | 61 +++++
.../operators/udf/RangeBoundaryBuilder.java | 74 ++++++
.../runtime/operators/udf/RemoveRangeIndex.java | 29 +++
.../org/apache/flink/api/scala/DataSet.scala | 56 ++++
.../test/javaApiOperators/PartitionITCase.java | 259 ++++++++++++++++++-
.../api/scala/operators/PartitionITCase.scala | 123 ++++++++-
25 files changed, 1358 insertions(+), 56 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/docs/apis/dataset_transformations.md
----------------------------------------------------------------------
diff --git a/docs/apis/dataset_transformations.md b/docs/apis/dataset_transformations.md
index c7debd3..8952170 100644
--- a/docs/apis/dataset_transformations.md
+++ b/docs/apis/dataset_transformations.md
@@ -1950,7 +1950,7 @@ Not supported.
### Hash-Partition
Hash-partitions a DataSet on a given key.
-Keys can be specified as key expressions or field position keys (see [Reduce examples](#reduce-on-grouped-dataset) for how to specify keys).
+Keys can be specified as position keys, expression keys, and key selector functions (see [Reduce examples](#reduce-on-grouped-dataset) for how to specify keys).
<div class="codetabs" markdown="1">
<div data-lang="java" markdown="1">
@@ -1981,6 +1981,41 @@ Not supported.
</div>
</div>
+### Range-Partition
+
+Range-partitions a DataSet on a given key.
+Keys can be specified as position keys, expression keys, and key selector functions (see [Reduce examples](#reduce-on-grouped-dataset) for how to specify keys).
+
+<div class="codetabs" markdown="1">
+<div data-lang="java" markdown="1">
+
+~~~java
+DataSet<Tuple2<String, Integer>> in = // [...]
+// range-partition DataSet by String value and apply a MapPartition transformation.
+DataSet<Tuple2<String, String>> out = in.partitionByRange(0)
+ .mapPartition(new PartitionMapper());
+~~~
+
+</div>
+<div data-lang="scala" markdown="1">
+
+~~~scala
+val in: DataSet[(String, Int)] = // [...]
+// range-partition DataSet by String value and apply a MapPartition transformation.
+val out = in.partitionByRange(0).mapPartition { ... }
+~~~
+
+</div>
+<div data-lang="python" markdown="1">
+
+~~~python
+Not supported.
+~~~
+
+</div>
+</div>
+
+
### Sort Partition
Locally sorts all partitions of a DataSet on a specified field in a specified order.
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/docs/apis/programming_guide.md
----------------------------------------------------------------------
diff --git a/docs/apis/programming_guide.md b/docs/apis/programming_guide.md
index 71a5e26..fb446f1 100644
--- a/docs/apis/programming_guide.md
+++ b/docs/apis/programming_guide.md
@@ -733,7 +733,7 @@ DataSet<String> result = in.rebalance()
<tr>
<td><strong>Hash-Partition</strong></td>
<td>
- <p>Hash-partitions a data set on a given key. Keys can be specified as key-selector functions or field position keys.</p>
+ <p>Hash-partitions a data set on a given key. Keys can be specified as position keys, expression keys, and key selector functions.</p>
{% highlight java %}
DataSet<Tuple2<String,Integer>> in = // [...]
DataSet<Integer> result = in.partitionByHash(0)
@@ -742,6 +742,17 @@ DataSet<Integer> result = in.partitionByHash(0)
</td>
</tr>
<tr>
+ <td><strong>Range-Partition</strong></td>
+ <td>
+ <p>Range-partitions a data set on a given key. Keys can be specified as position keys, expression keys, and key selector functions.</p>
+{% highlight java %}
+DataSet<Tuple2<String,Integer>> in = // [...]
+DataSet<Integer> result = in.partitionByRange(0)
+ .mapPartition(new PartitionMapper());
+{% endhighlight %}
+ </td>
+ </tr>
+ <tr>
<td><strong>Custom Partitioning</strong></td>
<td>
<p>Manually specify a partitioning over the data.
@@ -1012,14 +1023,23 @@ val result: DataSet[(Int, String)] = data1.rebalance().map(...)
<tr>
<td><strong>Hash-Partition</strong></td>
<td>
- <p>Hash-partitions a data set on a given key. Keys can be specified as key-selector functions, tuple positions
- or case class fields.</p>
+ <p>Hash-partitions a data set on a given key. Keys can be specified as position keys, expression keys, and key selector functions.</p>
{% highlight scala %}
val in: DataSet[(Int, String)] = // [...]
val result = in.partitionByHash(0).mapPartition { ... }
{% endhighlight %}
</td>
</tr>
+ <tr>
+ <td><strong>Range-Partition</strong></td>
+ <td>
+ <p>Range-partitions a data set on a given key. Keys can be specified as position keys, expression keys, and key selector functions.</p>
+{% highlight scala %}
+val in: DataSet[(Int, String)] = // [...]
+val result = in.partitionByRange(0).mapPartition { ... }
+{% endhighlight %}
+ </td>
+ </tr>
</tr>
<tr>
<td><strong>Custom Partitioning</strong></td>
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-clients/src/test/java/org/apache/flink/client/program/ExecutionPlanAfterExecutionTest.java
----------------------------------------------------------------------
diff --git a/flink-clients/src/test/java/org/apache/flink/client/program/ExecutionPlanAfterExecutionTest.java b/flink-clients/src/test/java/org/apache/flink/client/program/ExecutionPlanAfterExecutionTest.java
index 116c1e6..2bffba9 100644
--- a/flink-clients/src/test/java/org/apache/flink/client/program/ExecutionPlanAfterExecutionTest.java
+++ b/flink-clients/src/test/java/org/apache/flink/client/program/ExecutionPlanAfterExecutionTest.java
@@ -22,11 +22,12 @@ import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.LocalEnvironment;
+import org.apache.flink.api.java.aggregation.Aggregations;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
-
+import org.apache.flink.api.java.tuple.Tuple2;
import org.junit.Test;
-import static org.junit.Assert.*;
+import static org.junit.Assert.fail;
@SuppressWarnings("serial")
public class ExecutionPlanAfterExecutionTest implements java.io.Serializable {
@@ -72,4 +73,32 @@ public class ExecutionPlanAfterExecutionTest implements java.io.Serializable {
fail("Cannot run both #getExecutionPlan and #execute. Message: "+e.getMessage());
}
}
+
+ @Test
+ public void testGetExecutionPlanOfRangePartition() {
+ ExecutionEnvironment env = new LocalEnvironment();
+ env.getConfig().disableSysoutLogging();
+
+ DataSet<Integer> baseSet = env.fromElements(1, 2);
+
+ DataSet<Tuple2<Integer, Integer>> result = baseSet
+ .map(new MapFunction<Integer, Tuple2<Integer, Integer>>() {
+ @Override
+ public Tuple2<Integer, Integer> map(Integer value) throws Exception {
+ return new Tuple2(value, value * 2);
+ }
+ })
+ .partitionByRange(0)
+ .aggregate(Aggregations.MAX, 1);
+ result.output(new DiscardingOutputFormat<Tuple2<Integer, Integer>>());
+
+ try {
+ env.getExecutionPlan();
+ env.execute();
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ fail("Cannot run both #getExecutionPlan and #execute.");
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-core/src/main/java/org/apache/flink/api/common/distributions/CommonRangeBoundaries.java
----------------------------------------------------------------------
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/distributions/CommonRangeBoundaries.java b/flink-core/src/main/java/org/apache/flink/api/common/distributions/CommonRangeBoundaries.java
new file mode 100644
index 0000000..2b1daff
--- /dev/null
+++ b/flink-core/src/main/java/org/apache/flink/api/common/distributions/CommonRangeBoundaries.java
@@ -0,0 +1,77 @@
+/*
+ * 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.api.common.distributions;
+
+import org.apache.flink.api.common.typeutils.TypeComparator;
+
+public class CommonRangeBoundaries<T> implements RangeBoundaries<T> {
+ private final TypeComparator<T> typeComparator;
+ private final Object[][] boundaries;
+ private final TypeComparator[] flatComparators;
+ private final Object[] keys;
+
+ public CommonRangeBoundaries(TypeComparator<T> typeComparators, Object[][] boundaries) {
+ this.typeComparator = typeComparators;
+ this.flatComparators = typeComparators.getFlatComparators();
+ this.keys = new Object[flatComparators.length];
+ this.boundaries = boundaries;
+ }
+
+ @Override
+ public int getRangeIndex(T record) {
+ return binarySearch(record);
+ }
+
+ // Search the range index of input record.
+ private int binarySearch(T record) {
+ int low = 0;
+ int high = this.boundaries.length - 1;
+ typeComparator.extractKeys(record, keys, 0);
+
+ while (low <= high) {
+ final int mid = (low + high) >>> 1;
+ final int result = compareKeys(flatComparators, keys, this.boundaries[mid]);
+
+ if (result > 0) {
+ low = mid + 1;
+ } else if (result < 0) {
+ high = mid - 1;
+ } else {
+ return mid;
+ }
+ }
+ // key not found, but the low index is the target
+ // bucket, since the boundaries are the upper bound
+ return low;
+ }
+
+ private int compareKeys(TypeComparator[] flatComparators, Object[] keys, Object[] boundary) {
+ if (flatComparators.length != keys.length || flatComparators.length != boundary.length) {
+ throw new RuntimeException("Can not compare keys with boundary due to mismatched length.");
+ }
+
+ for (int i=0; i<flatComparators.length; i++) {
+ int result = flatComparators[i].compare(keys[i], boundary[i]);
+ if (result != 0) {
+ return result;
+ }
+ }
+
+ return 0;
+ }
+}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-core/src/main/java/org/apache/flink/api/common/distributions/DataDistribution.java
----------------------------------------------------------------------
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/distributions/DataDistribution.java b/flink-core/src/main/java/org/apache/flink/api/common/distributions/DataDistribution.java
index ebf1319..e04299e 100644
--- a/flink-core/src/main/java/org/apache/flink/api/common/distributions/DataDistribution.java
+++ b/flink-core/src/main/java/org/apache/flink/api/common/distributions/DataDistribution.java
@@ -22,7 +22,6 @@ package org.apache.flink.api.common.distributions;
import java.io.Serializable;
import org.apache.flink.core.io.IOReadableWritable;
-import org.apache.flink.types.Key;
public interface DataDistribution extends IOReadableWritable, Serializable {
@@ -46,7 +45,7 @@ public interface DataDistribution extends IOReadableWritable, Serializable {
*
* @return A record whose values act as bucket boundaries for the specified bucket.
*/
- Key<?>[] getBucketBoundary(int bucketNum, int totalNumBuckets);
+ Object[] getBucketBoundary(int bucketNum, int totalNumBuckets);
/**
* The number of fields in the (composite) key. This determines how many fields in the records define
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-core/src/main/java/org/apache/flink/api/common/distributions/RangeBoundaries.java
----------------------------------------------------------------------
diff --git a/flink-core/src/main/java/org/apache/flink/api/common/distributions/RangeBoundaries.java b/flink-core/src/main/java/org/apache/flink/api/common/distributions/RangeBoundaries.java
new file mode 100644
index 0000000..b7f6042
--- /dev/null
+++ b/flink-core/src/main/java/org/apache/flink/api/common/distributions/RangeBoundaries.java
@@ -0,0 +1,36 @@
+/*
+ * 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.api.common.distributions;
+
+import java.io.Serializable;
+
+/**
+ * RangeBoundaries is used to split the records into multiple ranges.
+ *
+ * @param <T> The boundary type.
+ */
+public interface RangeBoundaries<T> extends Serializable {
+
+ /**
+ * Get the range index of record.
+ *
+ * @param record The input record.
+ * @return The range index.
+ */
+ int getRangeIndex(T record);
+}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-java/src/main/java/org/apache/flink/api/java/DataSet.java
----------------------------------------------------------------------
diff --git a/flink-java/src/main/java/org/apache/flink/api/java/DataSet.java b/flink-java/src/main/java/org/apache/flink/api/java/DataSet.java
index cd63bcb..fd4e050 100644
--- a/flink-java/src/main/java/org/apache/flink/api/java/DataSet.java
+++ b/flink-java/src/main/java/org/apache/flink/api/java/DataSet.java
@@ -1246,7 +1246,49 @@ public abstract class DataSet<T> {
final TypeInformation<K> keyType = TypeExtractor.getKeySelectorTypes(keyExtractor, getType());
return new PartitionOperator<T>(this, PartitionMethod.HASH, new Keys.SelectorFunctionKeys<T, K>(clean(keyExtractor), this.getType(), keyType), Utils.getCallLocationName());
}
-
+
+ /**
+ * Range-partitions a DataSet on the specified key fields.
+ * <p>
+ * <b>Important:</b>This operation requires an extra pass over the DataSet to compute the range boundaries and
+ * shuffles the whole DataSet over the network. This can take significant amount of time.
+ *
+ * @param fields The field indexes on which the DataSet is range-partitioned.
+ * @return The partitioned DataSet.
+ */
+ public PartitionOperator<T> partitionByRange(int... fields) {
+ return new PartitionOperator<T>(this, PartitionMethod.RANGE, new Keys.ExpressionKeys<T>(fields, getType(), false), Utils.getCallLocationName());
+ }
+
+ /**
+ * Range-partitions a DataSet on the specified key fields.
+ * <p>
+ * <b>Important:</b>This operation requires an extra pass over the DataSet to compute the range boundaries and
+ * shuffles the whole DataSet over the network. This can take significant amount of time.
+ *
+ * @param fields The field expressions on which the DataSet is range-partitioned.
+ * @return The partitioned DataSet.
+ */
+ public PartitionOperator<T> partitionByRange(String... fields) {
+ return new PartitionOperator<T>(this, PartitionMethod.RANGE, new Keys.ExpressionKeys<T>(fields, getType()), Utils.getCallLocationName());
+ }
+
+ /**
+ * Range-partitions a DataSet using the specified KeySelector.
+ * <p>
+ * <b>Important:</b>This operation requires an extra pass over the DataSet to compute the range boundaries and
+ * shuffles the whole DataSet over the network. This can take significant amount of time.
+ *
+ * @param keyExtractor The KeyExtractor with which the DataSet is range-partitioned.
+ * @return The partitioned DataSet.
+ *
+ * @see KeySelector
+ */
+ public <K extends Comparable<K>> PartitionOperator<T> partitionByRange(KeySelector<T, K> keyExtractor) {
+ final TypeInformation<K> keyType = TypeExtractor.getKeySelectorTypes(keyExtractor, getType());
+ return new PartitionOperator<T>(this, PartitionMethod.RANGE, new Keys.SelectorFunctionKeys<T, K>(clean(keyExtractor), this.getType(), keyType), Utils.getCallLocationName());
+ }
+
/**
* Partitions a tuple DataSet on the specified key fields using a custom partitioner.
* This method takes the key position to partition on, and a partitioner that accepts the key type.
@@ -1393,7 +1435,7 @@ public abstract class DataSet<T> {
public DataSink<T> writeAsText(String filePath) {
return output(new TextOutputFormat<T>(new Path(filePath)));
}
-
+
/**
* Writes a DataSet as text file(s) to the specified location.<br>
* For each element of the DataSet the result of {@link Object#toString()} is written.
@@ -1410,7 +1452,7 @@ public abstract class DataSet<T> {
tof.setWriteMode(writeMode);
return output(tof);
}
-
+
/**
* Writes a DataSet as text file(s) to the specified location.<br>
* For each element of the DataSet the result of {@link TextFormatter#format(Object)} is written.
@@ -1441,7 +1483,7 @@ public abstract class DataSet<T> {
public DataSink<String> writeAsFormattedText(String filePath, WriteMode writeMode, TextFormatter<T> formatter) {
return map(new FormattingMapper<T>(clean(formatter))).writeAsText(filePath, writeMode);
}
-
+
/**
* Writes a {@link Tuple} DataSet as CSV file(s) to the specified location.<br>
* <b>Note: Only a Tuple DataSet can written as a CSV file.</b><br>
@@ -1459,7 +1501,7 @@ public abstract class DataSet<T> {
public DataSink<T> writeAsCsv(String filePath) {
return writeAsCsv(filePath, CsvOutputFormat.DEFAULT_LINE_DELIMITER, CsvOutputFormat.DEFAULT_FIELD_DELIMITER);
}
-
+
/**
* Writes a {@link Tuple} DataSet as CSV file(s) to the specified location.<br>
* <b>Note: Only a Tuple DataSet can written as a CSV file.</b><br>
@@ -1478,7 +1520,7 @@ public abstract class DataSet<T> {
public DataSink<T> writeAsCsv(String filePath, WriteMode writeMode) {
return internalWriteAsCsv(new Path(filePath),CsvOutputFormat.DEFAULT_LINE_DELIMITER, CsvOutputFormat.DEFAULT_FIELD_DELIMITER, writeMode);
}
-
+
/**
* Writes a {@link Tuple} DataSet as CSV file(s) to the specified location with the specified field and line delimiters.<br>
* <b>Note: Only a Tuple DataSet can written as a CSV file.</b><br>
@@ -1688,4 +1730,5 @@ public abstract class DataSet<T> {
}
}
+
}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-java/src/main/java/org/apache/flink/api/java/operators/PartitionOperator.java
----------------------------------------------------------------------
diff --git a/flink-java/src/main/java/org/apache/flink/api/java/operators/PartitionOperator.java b/flink-java/src/main/java/org/apache/flink/api/java/operators/PartitionOperator.java
index bf9c8e8..dd9dfb6 100644
--- a/flink-java/src/main/java/org/apache/flink/api/java/operators/PartitionOperator.java
+++ b/flink-java/src/main/java/org/apache/flink/api/java/operators/PartitionOperator.java
@@ -18,6 +18,8 @@
package org.apache.flink.api.java.operators;
+import com.google.common.base.Preconditions;
+
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.common.operators.Operator;
@@ -33,8 +35,6 @@ import org.apache.flink.api.java.operators.translation.KeyRemovingMapper;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.TupleTypeInfo;
-import com.google.common.base.Preconditions;
-
/**
* This operator represents a partitioning.
*
@@ -74,8 +74,7 @@ public class PartitionOperator<T> extends SingleInputOperator<T, T, PartitionOpe
Preconditions.checkNotNull(pMethod);
Preconditions.checkArgument(pKeys != null || pMethod == PartitionMethod.REBALANCE, "Partitioning requires keys");
Preconditions.checkArgument(pMethod != PartitionMethod.CUSTOM || customPartitioner != null, "Custom partioning requires a partitioner.");
- Preconditions.checkArgument(pMethod != PartitionMethod.RANGE, "Range partitioning is not yet supported");
-
+
if (pKeys instanceof Keys.ExpressionKeys<?> && !(input.getType() instanceof CompositeType) ) {
throw new IllegalArgumentException("Hash Partitioning with key fields only possible on Tuple or POJO DataSets");
}
@@ -122,7 +121,7 @@ public class PartitionOperator<T> extends SingleInputOperator<T, T, PartitionOpe
return noop;
}
- else if (pMethod == PartitionMethod.HASH || pMethod == PartitionMethod.CUSTOM) {
+ else if (pMethod == PartitionMethod.HASH || pMethod == PartitionMethod.CUSTOM || pMethod == PartitionMethod.RANGE) {
if (pKeys instanceof Keys.ExpressionKeys) {
@@ -148,9 +147,6 @@ public class PartitionOperator<T> extends SingleInputOperator<T, T, PartitionOpe
}
}
- else if (pMethod == PartitionMethod.RANGE) {
- throw new UnsupportedOperationException("Range partitioning not yet supported");
- }
else {
throw new UnsupportedOperationException("Unsupported partitioning method: " + pMethod.name());
}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/main/java/org/apache/flink/optimizer/Optimizer.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/main/java/org/apache/flink/optimizer/Optimizer.java b/flink-optimizer/src/main/java/org/apache/flink/optimizer/Optimizer.java
index ed3cbd5..d668cbe 100644
--- a/flink-optimizer/src/main/java/org/apache/flink/optimizer/Optimizer.java
+++ b/flink-optimizer/src/main/java/org/apache/flink/optimizer/Optimizer.java
@@ -42,6 +42,7 @@ import org.apache.flink.optimizer.plan.SinkJoinerPlanNode;
import org.apache.flink.optimizer.plan.SinkPlanNode;
import org.apache.flink.optimizer.postpass.OptimizerPostPass;
import org.apache.flink.configuration.ConfigConstants;
+import org.apache.flink.optimizer.traversals.RangePartitionRewriter;
import org.apache.flink.util.InstantiationUtil;
import org.slf4j.Logger;
@@ -513,7 +514,9 @@ public class Optimizer {
OptimizedPlan plan = new PlanFinalizer().createFinalPlan(bestPlanSinks, program.getJobName(), program);
plan.accept(new BinaryUnionReplacer());
-
+
+ plan.accept(new RangePartitionRewriter(plan));
+
// post pass the plan. this is the phase where the serialization and comparator code is set
postPasser.postPass(plan);
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/main/java/org/apache/flink/optimizer/dag/PartitionNode.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/main/java/org/apache/flink/optimizer/dag/PartitionNode.java b/flink-optimizer/src/main/java/org/apache/flink/optimizer/dag/PartitionNode.java
index 33383cb..65a6e02 100644
--- a/flink-optimizer/src/main/java/org/apache/flink/optimizer/dag/PartitionNode.java
+++ b/flink-optimizer/src/main/java/org/apache/flink/optimizer/dag/PartitionNode.java
@@ -23,6 +23,8 @@ import java.util.Collections;
import java.util.List;
import org.apache.flink.api.common.functions.Partitioner;
+import org.apache.flink.api.common.operators.Order;
+import org.apache.flink.api.common.operators.Ordering;
import org.apache.flink.api.common.operators.SemanticProperties;
import org.apache.flink.api.common.operators.SingleInputSemanticProperties;
import org.apache.flink.api.common.operators.base.PartitionOperatorBase;
@@ -119,7 +121,14 @@ public class PartitionNode extends SingleInputNode {
rgps.setCustomPartitioned(this.keys, this.customPartitioner);
break;
case RANGE:
- throw new UnsupportedOperationException("Not yet supported");
+ // Initiate Ordering as ascending here as no order parameter in API level,
+ // we could revisit this while order is required in future optimization.
+ Ordering ordering = new Ordering();
+ for (int field : this.keys) {
+ ordering.appendOrdering(field, null, Order.ASCENDING);
+ }
+ rgps.setRangePartitioned(ordering);
+ break;
default:
throw new IllegalArgumentException("Invalid partition method");
}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/AbstractJoinDescriptor.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/AbstractJoinDescriptor.java b/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/AbstractJoinDescriptor.java
index 2b634ae..6c2776e 100644
--- a/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/AbstractJoinDescriptor.java
+++ b/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/AbstractJoinDescriptor.java
@@ -142,9 +142,9 @@ public abstract class AbstractJoinDescriptor extends OperatorDescriptorDual {
else if(produced1.getPartitioning() == PartitioningProperty.RANGE_PARTITIONED &&
produced2.getPartitioning() == PartitioningProperty.RANGE_PARTITIONED) {
- // both are range partitioned, check that partitioning fields are equivalently chosen
- return checkEquivalentFieldPositionsInKeyFields(
- produced1.getPartitioningFields(), produced2.getPartitioningFields());
+ // Return false anyway now, we need both the partition key and data distribution
+ // information to make sure whether the range partitions are equivalent.
+ return false;
}
else if(produced1.getPartitioning() == PartitioningProperty.CUSTOM_PARTITIONING &&
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/CoGroupDescriptor.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/CoGroupDescriptor.java b/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/CoGroupDescriptor.java
index 571d6e6..b99b1c1 100644
--- a/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/CoGroupDescriptor.java
+++ b/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/CoGroupDescriptor.java
@@ -151,9 +151,9 @@ public class CoGroupDescriptor extends OperatorDescriptorDual {
else if(produced1.getPartitioning() == PartitioningProperty.RANGE_PARTITIONED &&
produced2.getPartitioning() == PartitioningProperty.RANGE_PARTITIONED) {
- // both are range partitioned, check that partitioning fields are equivalently chosen
- return checkEquivalentFieldPositionsInKeyFields(
- produced1.getPartitioningFields(), produced2.getPartitioningFields());
+ // Return false anyway now, we need both the partition key and data distribution
+ // information to make sure whether the range partitions are equivalent.
+ return false;
}
else if(produced1.getPartitioning() == PartitioningProperty.CUSTOM_PARTITIONING &&
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/GroupReduceWithCombineProperties.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/GroupReduceWithCombineProperties.java b/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/GroupReduceWithCombineProperties.java
index 86863d2..a4f295d 100644
--- a/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/GroupReduceWithCombineProperties.java
+++ b/flink-optimizer/src/main/java/org/apache/flink/optimizer/operators/GroupReduceWithCombineProperties.java
@@ -121,6 +121,9 @@ public final class GroupReduceWithCombineProperties extends OperatorDescriptorSi
Channel toReducer = new Channel(combiner);
toReducer.setShipStrategy(in.getShipStrategy(), in.getShipStrategyKeys(),
in.getShipStrategySortOrder(), in.getDataExchangeMode());
+ if (in.getShipStrategy() == ShipStrategyType.PARTITION_RANGE) {
+ toReducer.setDataDistribution(in.getDataDistribution());
+ }
toReducer.setLocalStrategy(LocalStrategy.COMBININGSORT, in.getLocalStrategyKeys(),
in.getLocalStrategySortOrder());
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/main/java/org/apache/flink/optimizer/plan/Channel.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/main/java/org/apache/flink/optimizer/plan/Channel.java b/flink-optimizer/src/main/java/org/apache/flink/optimizer/plan/Channel.java
index a4448c6..508cc95 100644
--- a/flink-optimizer/src/main/java/org/apache/flink/optimizer/plan/Channel.java
+++ b/flink-optimizer/src/main/java/org/apache/flink/optimizer/plan/Channel.java
@@ -134,6 +134,10 @@ public class Channel implements EstimateProvider, Cloneable, DumpableConnection<
public PlanNode getSource() {
return this.source;
}
+
+ public void setSource(PlanNode source) {
+ this.source = source;
+ }
/**
* Sets the target of this Channel.
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/main/java/org/apache/flink/optimizer/plantranslate/JobGraphGenerator.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/main/java/org/apache/flink/optimizer/plantranslate/JobGraphGenerator.java b/flink-optimizer/src/main/java/org/apache/flink/optimizer/plantranslate/JobGraphGenerator.java
index 1546631..159a94a 100644
--- a/flink-optimizer/src/main/java/org/apache/flink/optimizer/plantranslate/JobGraphGenerator.java
+++ b/flink-optimizer/src/main/java/org/apache/flink/optimizer/plantranslate/JobGraphGenerator.java
@@ -1145,8 +1145,7 @@ public class JobGraphGenerator implements Visitor<PlanNode> {
if (dataDistribution != null) {
sourceConfig.setOutputDataDistribution(dataDistribution, outputIndex);
} else {
- throw new RuntimeException("Range partitioning requires data distribution");
- // TODO: inject code and configuration for automatic histogram generation
+ throw new RuntimeException("Range partitioning requires data distribution.");
}
}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/main/java/org/apache/flink/optimizer/traversals/RangePartitionRewriter.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/main/java/org/apache/flink/optimizer/traversals/RangePartitionRewriter.java b/flink-optimizer/src/main/java/org/apache/flink/optimizer/traversals/RangePartitionRewriter.java
new file mode 100644
index 0000000..1110f23
--- /dev/null
+++ b/flink-optimizer/src/main/java/org/apache/flink/optimizer/traversals/RangePartitionRewriter.java
@@ -0,0 +1,229 @@
+/*
+ * 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.optimizer.traversals;
+
+import org.apache.flink.api.common.distributions.CommonRangeBoundaries;
+import org.apache.flink.api.common.functions.Partitioner;
+import org.apache.flink.api.common.operators.Order;
+import org.apache.flink.api.common.operators.Ordering;
+import org.apache.flink.api.common.operators.UnaryOperatorInformation;
+import org.apache.flink.api.common.operators.base.GroupReduceOperatorBase;
+import org.apache.flink.api.common.operators.base.MapOperatorBase;
+import org.apache.flink.api.common.operators.base.MapPartitionOperatorBase;
+import org.apache.flink.api.common.operators.util.FieldList;
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeutils.TypeComparatorFactory;
+import org.apache.flink.optimizer.costs.Costs;
+import org.apache.flink.optimizer.dataproperties.GlobalProperties;
+import org.apache.flink.optimizer.dataproperties.LocalProperties;
+import org.apache.flink.runtime.io.network.DataExchangeMode;
+import org.apache.flink.runtime.operators.udf.AssignRangeIndex;
+import org.apache.flink.runtime.operators.udf.RemoveRangeIndex;
+import org.apache.flink.runtime.operators.udf.RangeBoundaryBuilder;
+import org.apache.flink.api.java.functions.SampleInCoordinator;
+import org.apache.flink.api.java.functions.SampleInPartition;
+import org.apache.flink.api.java.sampling.IntermediateSampleData;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.api.java.typeutils.TupleTypeInfo;
+import org.apache.flink.api.java.typeutils.TypeExtractor;
+import org.apache.flink.optimizer.dag.GroupReduceNode;
+import org.apache.flink.optimizer.dag.MapNode;
+import org.apache.flink.optimizer.dag.MapPartitionNode;
+import org.apache.flink.optimizer.dag.TempMode;
+import org.apache.flink.optimizer.plan.Channel;
+import org.apache.flink.optimizer.plan.NamedChannel;
+import org.apache.flink.optimizer.plan.OptimizedPlan;
+import org.apache.flink.optimizer.plan.PlanNode;
+import org.apache.flink.optimizer.plan.SingleInputPlanNode;
+import org.apache.flink.optimizer.util.Utils;
+import org.apache.flink.runtime.operators.DriverStrategy;
+import org.apache.flink.runtime.operators.shipping.ShipStrategyType;
+import org.apache.flink.util.Visitor;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ */
+public class RangePartitionRewriter implements Visitor<PlanNode> {
+
+ final static long SEED = 0;
+ final static String SIP_NAME = "RangePartition: LocalSample";
+ final static String SIC_NAME = "RangePartition: GlobalSample";
+ final static String RB_NAME = "RangePartition: Histogram";
+ final static String ARI_NAME = "RangePartition: PreparePartition";
+ final static String PR_NAME = "RangePartition: Partition";
+
+ final static int SAMPLES_PER_PARTITION = 1000;
+
+ final static IdPartitioner idPartitioner = new IdPartitioner();
+
+ final OptimizedPlan plan;
+
+ public RangePartitionRewriter(OptimizedPlan plan) {
+ this.plan = plan;
+ }
+
+ @Override
+ public boolean preVisit(PlanNode visitable) {
+ return true;
+ }
+
+ @Override
+ public void postVisit(PlanNode visitable) {
+ final Iterable<Channel> inputChannels = visitable.getInputs();
+ for (Channel channel : inputChannels) {
+ ShipStrategyType shipStrategy = channel.getShipStrategy();
+ // Make sure we only optimize the DAG for range partition, and do not optimize multi times.
+ if (shipStrategy == ShipStrategyType.PARTITION_RANGE && isOptimized(visitable)) {
+ PlanNode channelSource = channel.getSource();
+ List<Channel> newSourceOutputChannels = rewriteRangePartitionChannel(channel);
+ channelSource.getOutgoingChannels().remove(channel);
+ channelSource.getOutgoingChannels().addAll(newSourceOutputChannels);
+ }
+ }
+ }
+
+ private List<Channel> rewriteRangePartitionChannel(Channel channel) {
+ final List<Channel> sourceNewOutputChannels = new ArrayList<>();
+ final PlanNode sourceNode = channel.getSource();
+ final PlanNode targetNode = channel.getTarget();
+ final int sourceParallelism = sourceNode.getParallelism();
+ final int targetParallelism = targetNode.getParallelism();
+ final Costs defaultZeroCosts = new Costs(0, 0, 0);
+ final TypeComparatorFactory<?> comparator = Utils.getShipComparator(channel, this.plan.getOriginalPlan().getExecutionConfig());
+ // 1. Fixed size sample in each partitions.
+ final int sampleSize = SAMPLES_PER_PARTITION * targetParallelism;
+ final SampleInPartition sampleInPartition = new SampleInPartition(false, sampleSize, SEED);
+ final TypeInformation<?> sourceOutputType = sourceNode.getOptimizerNode().getOperator().getOperatorInfo().getOutputType();
+ final TypeInformation<IntermediateSampleData> isdTypeInformation = TypeExtractor.getForClass(IntermediateSampleData.class);
+ final UnaryOperatorInformation sipOperatorInformation = new UnaryOperatorInformation(sourceOutputType, isdTypeInformation);
+ final MapPartitionOperatorBase sipOperatorBase = new MapPartitionOperatorBase(sampleInPartition, sipOperatorInformation, SIP_NAME);
+ final MapPartitionNode sipNode = new MapPartitionNode(sipOperatorBase);
+ final Channel sipChannel = new Channel(sourceNode, TempMode.NONE);
+ sipChannel.setShipStrategy(ShipStrategyType.FORWARD, DataExchangeMode.PIPELINED);
+ final SingleInputPlanNode sipPlanNode = new SingleInputPlanNode(sipNode, SIP_NAME, sipChannel, DriverStrategy.MAP_PARTITION);
+ sipNode.setParallelism(sourceParallelism);
+ sipPlanNode.setParallelism(sourceParallelism);
+ sipPlanNode.initProperties(new GlobalProperties(), new LocalProperties());
+ sipPlanNode.setCosts(defaultZeroCosts);
+ sipChannel.setTarget(sipPlanNode);
+ this.plan.getAllNodes().add(sipPlanNode);
+ sourceNewOutputChannels.add(sipChannel);
+
+ // 2. Fixed size sample in a single coordinator.
+ final SampleInCoordinator sampleInCoordinator = new SampleInCoordinator(false, sampleSize, SEED);
+ final UnaryOperatorInformation sicOperatorInformation = new UnaryOperatorInformation(isdTypeInformation, sourceOutputType);
+ final GroupReduceOperatorBase sicOperatorBase = new GroupReduceOperatorBase(sampleInCoordinator, sicOperatorInformation, SIC_NAME);
+ final GroupReduceNode sicNode = new GroupReduceNode(sicOperatorBase);
+ final Channel sicChannel = new Channel(sipPlanNode, TempMode.NONE);
+ sicChannel.setShipStrategy(ShipStrategyType.FORWARD, DataExchangeMode.PIPELINED);
+ final SingleInputPlanNode sicPlanNode = new SingleInputPlanNode(sicNode, SIC_NAME, sicChannel, DriverStrategy.ALL_GROUP_REDUCE);
+ sicNode.setParallelism(1);
+ sicPlanNode.setParallelism(1);
+ sicPlanNode.initProperties(new GlobalProperties(), new LocalProperties());
+ sicPlanNode.setCosts(defaultZeroCosts);
+ sicChannel.setTarget(sicPlanNode);
+ sipPlanNode.addOutgoingChannel(sicChannel);
+ this.plan.getAllNodes().add(sicPlanNode);
+
+ // 3. Use sampled data to build range boundaries.
+ final RangeBoundaryBuilder rangeBoundaryBuilder = new RangeBoundaryBuilder(comparator, targetParallelism);
+ final TypeInformation<CommonRangeBoundaries> rbTypeInformation = TypeExtractor.getForClass(CommonRangeBoundaries.class);
+ final UnaryOperatorInformation rbOperatorInformation = new UnaryOperatorInformation(sourceOutputType, rbTypeInformation);
+ final MapPartitionOperatorBase rbOperatorBase = new MapPartitionOperatorBase(rangeBoundaryBuilder, rbOperatorInformation, RB_NAME);
+ final MapPartitionNode rbNode = new MapPartitionNode(rbOperatorBase);
+ final Channel rbChannel = new Channel(sicPlanNode, TempMode.NONE);
+ rbChannel.setShipStrategy(ShipStrategyType.FORWARD, DataExchangeMode.PIPELINED);
+ final SingleInputPlanNode rbPlanNode = new SingleInputPlanNode(rbNode, RB_NAME, rbChannel, DriverStrategy.MAP_PARTITION);
+ rbNode.setParallelism(1);
+ rbPlanNode.setParallelism(1);
+ rbPlanNode.initProperties(new GlobalProperties(), new LocalProperties());
+ rbPlanNode.setCosts(defaultZeroCosts);
+ rbChannel.setTarget(rbPlanNode);
+ sicPlanNode.addOutgoingChannel(rbChannel);
+ this.plan.getAllNodes().add(rbPlanNode);
+
+ // 4. Take range boundaries as broadcast input and take the tuple of partition id and record as output.
+ final AssignRangeIndex assignRangeIndex = new AssignRangeIndex(comparator);
+ final TypeInformation<Tuple2> ariOutputTypeInformation = new TupleTypeInfo<>(BasicTypeInfo.INT_TYPE_INFO, sourceOutputType);
+ final UnaryOperatorInformation ariOperatorInformation = new UnaryOperatorInformation(sourceOutputType, ariOutputTypeInformation);
+ final MapPartitionOperatorBase ariOperatorBase = new MapPartitionOperatorBase(assignRangeIndex, ariOperatorInformation, ARI_NAME);
+ final MapPartitionNode ariNode = new MapPartitionNode(ariOperatorBase);
+ final Channel ariChannel = new Channel(sourceNode, TempMode.NONE);
+ // To avoid deadlock, set the DataExchangeMode of channel between source node and this to Batch.
+ ariChannel.setShipStrategy(ShipStrategyType.FORWARD, DataExchangeMode.BATCH);
+ final SingleInputPlanNode ariPlanNode = new SingleInputPlanNode(ariNode, ARI_NAME, ariChannel, DriverStrategy.MAP_PARTITION);
+ ariNode.setParallelism(sourceParallelism);
+ ariPlanNode.setParallelism(sourceParallelism);
+ ariPlanNode.initProperties(new GlobalProperties(), new LocalProperties());
+ ariPlanNode.setCosts(defaultZeroCosts);
+ ariChannel.setTarget(ariPlanNode);
+ this.plan.getAllNodes().add(ariPlanNode);
+ sourceNewOutputChannels.add(ariChannel);
+
+ final NamedChannel broadcastChannel = new NamedChannel("RangeBoundaries", rbPlanNode);
+ broadcastChannel.setShipStrategy(ShipStrategyType.BROADCAST, DataExchangeMode.PIPELINED);
+ broadcastChannel.setTarget(ariPlanNode);
+ List<NamedChannel> broadcastChannels = new ArrayList<>(1);
+ broadcastChannels.add(broadcastChannel);
+ ariPlanNode.setBroadcastInputs(broadcastChannels);
+
+ // 5. Remove the partition id.
+ final Channel partChannel = new Channel(ariPlanNode, TempMode.NONE);
+ final FieldList keys = new FieldList(0);
+ partChannel.setShipStrategy(ShipStrategyType.PARTITION_CUSTOM, keys, idPartitioner, DataExchangeMode.PIPELINED);
+ ariPlanNode.addOutgoingChannel(partChannel);
+
+ final RemoveRangeIndex partitionIDRemoveWrapper = new RemoveRangeIndex();
+ final UnaryOperatorInformation prOperatorInformation = new UnaryOperatorInformation(ariOutputTypeInformation, sourceOutputType);
+ final MapOperatorBase prOperatorBase = new MapOperatorBase(partitionIDRemoveWrapper, prOperatorInformation, PR_NAME);
+ final MapNode prRemoverNode = new MapNode(prOperatorBase);
+ final SingleInputPlanNode prPlanNode = new SingleInputPlanNode(prRemoverNode, PR_NAME, partChannel, DriverStrategy.MAP);
+ partChannel.setTarget(prPlanNode);
+ prRemoverNode.setParallelism(targetParallelism);
+ prPlanNode.setParallelism(targetParallelism);
+ GlobalProperties globalProperties = new GlobalProperties();
+ globalProperties.setRangePartitioned(new Ordering(0, null, Order.ASCENDING));
+ prPlanNode.initProperties(globalProperties, new LocalProperties());
+ prPlanNode.setCosts(defaultZeroCosts);
+ this.plan.getAllNodes().add(prPlanNode);
+
+ // 6. Connect to target node.
+ channel.setSource(prPlanNode);
+ channel.setShipStrategy(ShipStrategyType.FORWARD, DataExchangeMode.PIPELINED);
+ prPlanNode.addOutgoingChannel(channel);
+
+ return sourceNewOutputChannels;
+ }
+
+
+ private boolean isOptimized(PlanNode node) {
+ return node.getNodeName() != PR_NAME;
+ }
+
+ static class IDPartitioner implements Partitioner<Integer> {
+
+ @Override
+ public int partition(Integer key, int numPartitions) {
+ return key;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/main/java/org/apache/flink/optimizer/util/Utils.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/main/java/org/apache/flink/optimizer/util/Utils.java b/flink-optimizer/src/main/java/org/apache/flink/optimizer/util/Utils.java
index ac44a09..1099028 100644
--- a/flink-optimizer/src/main/java/org/apache/flink/optimizer/util/Utils.java
+++ b/flink-optimizer/src/main/java/org/apache/flink/optimizer/util/Utils.java
@@ -21,11 +21,21 @@ package org.apache.flink.optimizer.util;
import java.util.Arrays;
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.api.common.operators.Operator;
import org.apache.flink.api.common.operators.Order;
import org.apache.flink.api.common.operators.Ordering;
import org.apache.flink.api.common.operators.util.FieldList;
import org.apache.flink.api.common.operators.util.FieldSet;
+import org.apache.flink.api.common.typeinfo.AtomicType;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeutils.CompositeType;
+import org.apache.flink.api.common.typeutils.TypeComparator;
+import org.apache.flink.api.common.typeutils.TypeComparatorFactory;
+import org.apache.flink.api.java.typeutils.runtime.RuntimeComparatorFactory;
import org.apache.flink.optimizer.CompilerException;
+import org.apache.flink.optimizer.plan.Channel;
+import org.apache.flink.optimizer.plan.PlanNode;
/**
@@ -71,6 +81,39 @@ public final class Utils {
throw new CompilerException();
}
}
+
+ public static TypeComparatorFactory<?> getShipComparator(Channel channel, ExecutionConfig executionConfig) {
+ PlanNode source = channel.getSource();
+ Operator<?> javaOp = source.getProgramOperator();
+ TypeInformation<?> type = javaOp.getOperatorInfo().getOutputType();
+ return createComparator(type, channel.getShipStrategyKeys(),
+ getSortOrders(channel.getShipStrategyKeys(), channel.getShipStrategySortOrder()), executionConfig);
+ }
+
+ private static <T> TypeComparatorFactory<?> createComparator(TypeInformation<T> typeInfo, FieldList keys, boolean[] sortOrder, ExecutionConfig executionConfig) {
+
+ TypeComparator<T> comparator;
+ if (typeInfo instanceof CompositeType) {
+ comparator = ((CompositeType<T>) typeInfo).createComparator(keys.toArray(), sortOrder, 0, executionConfig);
+ }
+ else if (typeInfo instanceof AtomicType) {
+ // handle grouping of atomic types
+ comparator = ((AtomicType<T>) typeInfo).createComparator(sortOrder[0], executionConfig);
+ }
+ else {
+ throw new RuntimeException("Unrecognized type: " + typeInfo);
+ }
+
+ return new RuntimeComparatorFactory<T>(comparator);
+ }
+
+ private static final boolean[] getSortOrders(FieldList keys, boolean[] orders) {
+ if (orders == null) {
+ orders = new boolean[keys.size()];
+ Arrays.fill(orders, true);
+ }
+ return orders;
+ }
// --------------------------------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-optimizer/src/test/java/org/apache/flink/optimizer/java/PartitionOperatorTest.java
----------------------------------------------------------------------
diff --git a/flink-optimizer/src/test/java/org/apache/flink/optimizer/java/PartitionOperatorTest.java b/flink-optimizer/src/test/java/org/apache/flink/optimizer/java/PartitionOperatorTest.java
index 7f5c209..ff4a3c8 100644
--- a/flink-optimizer/src/test/java/org/apache/flink/optimizer/java/PartitionOperatorTest.java
+++ b/flink-optimizer/src/test/java/org/apache/flink/optimizer/java/PartitionOperatorTest.java
@@ -21,18 +21,26 @@ package org.apache.flink.optimizer.java;
import static org.junit.Assert.*;
import java.util.Collections;
+import java.util.List;
import org.apache.flink.api.common.Plan;
+import org.apache.flink.api.common.functions.FilterFunction;
+import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
+import org.apache.flink.api.java.aggregation.Aggregations;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
+import org.apache.flink.api.java.operators.PartitionOperator;
import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.optimizer.plan.Channel;
import org.apache.flink.optimizer.plan.OptimizedPlan;
import org.apache.flink.optimizer.plan.SingleInputPlanNode;
import org.apache.flink.optimizer.plan.SinkPlanNode;
+import org.apache.flink.optimizer.plan.SourcePlanNode;
import org.apache.flink.optimizer.testfunctions.IdentityGroupReducerCombinable;
import org.apache.flink.optimizer.util.CompilerTestBase;
+import org.apache.flink.runtime.io.network.DataExchangeMode;
import org.apache.flink.runtime.operators.shipping.ShipStrategyType;
import org.junit.Test;
@@ -40,17 +48,17 @@ import org.junit.Test;
public class PartitionOperatorTest extends CompilerTestBase {
@Test
- public void testPartitionOperatorPreservesFields() {
+ public void testPartitionCustomOperatorPreservesFields() {
try {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
- DataSet<Tuple2<Long, Long>> data = env.fromCollection(Collections.singleton(new Tuple2<Long, Long>(0L, 0L)));
+ DataSet<Tuple2<Long, Long>> data = env.fromCollection(Collections.singleton(new Tuple2<>(0L, 0L)));
data.partitionCustom(new Partitioner<Long>() {
public int partition(Long key, int numPartitions) { return key.intValue(); }
}, 1)
.groupBy(1)
- .reduceGroup(new IdentityGroupReducerCombinable<Tuple2<Long,Long>>())
+ .reduceGroup(new IdentityGroupReducerCombinable<Tuple2<Long, Long>>())
.output(new DiscardingOutputFormat<Tuple2<Long, Long>>());
Plan p = env.createProgramPlan();
@@ -68,4 +76,112 @@ public class PartitionOperatorTest extends CompilerTestBase {
fail(e.getMessage());
}
}
+
+ @Test
+ public void testRangePartitionOperatorPreservesFields() {
+ try {
+ ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+
+ DataSet<Tuple2<Long, Long>> data = env.fromCollection(Collections.singleton(new Tuple2<>(0L, 0L)));
+
+ data.partitionByRange(1)
+ .groupBy(1)
+ .reduceGroup(new IdentityGroupReducerCombinable<Tuple2<Long,Long>>())
+ .output(new DiscardingOutputFormat<Tuple2<Long, Long>>());
+
+ Plan p = env.createProgramPlan();
+ OptimizedPlan op = compileNoStats(p);
+
+ SinkPlanNode sink = op.getDataSinks().iterator().next();
+ SingleInputPlanNode reducer = (SingleInputPlanNode) sink.getInput().getSource();
+ SingleInputPlanNode partitionNode = (SingleInputPlanNode)reducer.getInput().getSource();
+ SingleInputPlanNode partitionIDRemover = (SingleInputPlanNode) partitionNode.getInput().getSource();
+
+ assertEquals(ShipStrategyType.FORWARD, reducer.getInput().getShipStrategy());
+ assertEquals(ShipStrategyType.FORWARD, partitionNode.getInput().getShipStrategy());
+ assertEquals(ShipStrategyType.PARTITION_CUSTOM, partitionIDRemover.getInput().getShipStrategy());
+
+ SourcePlanNode sourcePlanNode = op.getDataSources().iterator().next();
+ List<Channel> sourceOutgoingChannels = sourcePlanNode.getOutgoingChannels();
+ assertEquals(2, sourceOutgoingChannels.size());
+ assertEquals(ShipStrategyType.FORWARD, sourceOutgoingChannels.get(0).getShipStrategy());
+ assertEquals(ShipStrategyType.FORWARD, sourceOutgoingChannels.get(1).getShipStrategy());
+ assertEquals(DataExchangeMode.PIPELINED, sourceOutgoingChannels.get(0).getDataExchangeMode());
+ assertEquals(DataExchangeMode.BATCH, sourceOutgoingChannels.get(1).getDataExchangeMode());
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ }
+
+ @Test
+ public void testRangePartitionOperatorPreservesFields2() {
+ try {
+ ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+
+ DataSet<Tuple2<Long, Long>> data = env.fromCollection(Collections.singleton(new Tuple2<>(0L, 0L)));
+
+ PartitionOperator<Tuple2<Long, Long>> rangePartitioned = data.partitionByRange(1);
+
+ rangePartitioned
+ .groupBy(1)
+ .reduceGroup(new IdentityGroupReducerCombinable<Tuple2<Long,Long>>())
+ .output(new DiscardingOutputFormat<Tuple2<Long, Long>>());
+
+ data
+ .groupBy(0)
+ .aggregate(Aggregations.SUM, 1)
+ .map(new MapFunction<Tuple2<Long, Long>, Long>() {
+ @Override
+ public Long map(Tuple2<Long, Long> value) throws Exception {
+ return value.f1;
+ }
+ })
+ .output(new DiscardingOutputFormat<Long>());
+
+ rangePartitioned
+ .filter(new FilterFunction<Tuple2<Long, Long>>() {
+ @Override
+ public boolean filter(Tuple2<Long, Long> value) throws Exception {
+ return value.f0 % 2 == 0;
+ }
+ })
+ .output(new DiscardingOutputFormat<Tuple2<Long, Long>>());
+
+
+ Plan p = env.createProgramPlan();
+ OptimizedPlan op = compileNoStats(p);
+
+ SinkPlanNode sink = op.getDataSinks().iterator().next();
+ SingleInputPlanNode reducer = (SingleInputPlanNode) sink.getInput().getSource();
+ SingleInputPlanNode partitionNode = (SingleInputPlanNode)reducer.getInput().getSource();
+ SingleInputPlanNode partitionIDRemover = (SingleInputPlanNode) partitionNode.getInput().getSource();
+
+ assertEquals(ShipStrategyType.FORWARD, reducer.getInput().getShipStrategy());
+ assertEquals(ShipStrategyType.FORWARD, partitionNode.getInput().getShipStrategy());
+ assertEquals(ShipStrategyType.PARTITION_CUSTOM, partitionIDRemover.getInput().getShipStrategy());
+
+ SourcePlanNode sourcePlanNode = op.getDataSources().iterator().next();
+ List<Channel> sourceOutgoingChannels = sourcePlanNode.getOutgoingChannels();
+ assertEquals(3, sourceOutgoingChannels.size());
+ assertEquals(ShipStrategyType.FORWARD, sourceOutgoingChannels.get(0).getShipStrategy());
+ assertEquals(ShipStrategyType.FORWARD, sourceOutgoingChannels.get(1).getShipStrategy());
+ assertEquals(ShipStrategyType.FORWARD, sourceOutgoingChannels.get(2).getShipStrategy());
+ assertEquals(DataExchangeMode.PIPELINED, sourceOutgoingChannels.get(0).getDataExchangeMode());
+ assertEquals(DataExchangeMode.PIPELINED, sourceOutgoingChannels.get(1).getDataExchangeMode());
+ assertEquals(DataExchangeMode.BATCH, sourceOutgoingChannels.get(2).getDataExchangeMode());
+
+ List<Channel> partitionOutputChannels = partitionNode.getOutgoingChannels();
+ assertEquals(2, partitionOutputChannels.size());
+ assertEquals(ShipStrategyType.FORWARD, partitionOutputChannels.get(0).getShipStrategy());
+ assertEquals(ShipStrategyType.FORWARD, partitionOutputChannels.get(1).getShipStrategy());
+ assertEquals(DataExchangeMode.PIPELINED, partitionOutputChannels.get(0).getDataExchangeMode());
+ assertEquals(DataExchangeMode.PIPELINED, partitionOutputChannels.get(1).getDataExchangeMode());
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-runtime/src/main/java/org/apache/flink/runtime/operators/shipping/OutputEmitter.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/shipping/OutputEmitter.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/shipping/OutputEmitter.java
index 082b764..92e3787 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/shipping/OutputEmitter.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/shipping/OutputEmitter.java
@@ -28,9 +28,10 @@ import org.apache.flink.runtime.plugable.SerializationDelegate;
* The output emitter decides to which of the possibly multiple output channels a record is sent.
* It implement routing based on hash-partitioning, broadcasting, round-robin, custom partition
* functions, etc.
- *
+ *
* @param <T> The type of the element handled by the emitter.
*/
+
public class OutputEmitter<T> implements ChannelSelector<SerializationDelegate<T>> {
/** the shipping strategy used by this output emitter */
@@ -44,8 +45,16 @@ public class OutputEmitter<T> implements ChannelSelector<SerializationDelegate<T
/** the comparator for hashing / sorting */
private final TypeComparator<T> comparator;
-
+
+ private Object[][] partitionBoundaries; // the partition boundaries for range partitioning
+
+ private DataDistribution distribution; // the data distribution to create the partition boundaries for range partitioning
+
private final Partitioner<Object> partitioner;
+
+ private TypeComparator[] flatComparators;
+
+ private Object[] keys;
private Object[] extractedKeys;
@@ -77,34 +86,40 @@ public class OutputEmitter<T> implements ChannelSelector<SerializationDelegate<T
@SuppressWarnings("unchecked")
public OutputEmitter(ShipStrategyType strategy, int indexInSubtaskGroup,
- TypeComparator<T> comparator, Partitioner<?> partitioner, DataDistribution distr) {
+ TypeComparator<T> comparator, Partitioner<?> partitioner, DataDistribution distribution) {
if (strategy == null) {
throw new NullPointerException();
}
-
+
this.strategy = strategy;
this.nextChannelToSendTo = indexInSubtaskGroup;
this.comparator = comparator;
this.partitioner = (Partitioner<Object>) partitioner;
-
+ this.distribution = distribution;
+
+
switch (strategy) {
case PARTITION_CUSTOM:
extractedKeys = new Object[1];
case FORWARD:
case PARTITION_HASH:
- case PARTITION_RANGE:
case PARTITION_RANDOM:
case PARTITION_FORCED_REBALANCE:
channels = new int[1];
+ break;
+ case PARTITION_RANGE:
+ channels = new int[1];
+ if (comparator != null) {
+ this.flatComparators = comparator.getFlatComparators();
+ this.keys = new Object[flatComparators.length];
+ }
+ break;
case BROADCAST:
break;
default:
throw new IllegalArgumentException("Invalid shipping strategy for OutputEmitter: " + strategy.name());
}
-
- if ((strategy == ShipStrategyType.PARTITION_RANGE) && distr == null) {
- throw new NullPointerException("Data distribution must not be null when the ship strategy is range partitioning.");
- }
+
if (strategy == ShipStrategyType.PARTITION_CUSTOM && partitioner == null) {
throw new NullPointerException("Partitioner must not be null when the ship strategy is set to custom partitioning.");
}
@@ -128,6 +143,8 @@ public class OutputEmitter<T> implements ChannelSelector<SerializationDelegate<T
return broadcast(numberOfChannels);
case PARTITION_CUSTOM:
return customPartition(record.getInstance(), numberOfChannels);
+ case PARTITION_RANGE:
+ return rangePartition(record.getInstance(), numberOfChannels);
default:
throw new UnsupportedOperationException("Unsupported distribution strategy: " + strategy.name());
}
@@ -202,8 +219,54 @@ public class OutputEmitter<T> implements ChannelSelector<SerializationDelegate<T
return k;
}
-
+
+ private final int[] rangePartition(final T record, int numberOfChannels) {
+ if (this.channels == null || this.channels.length != 1) {
+ this.channels = new int[1];
+ }
+
+ if (this.partitionBoundaries == null) {
+ this.partitionBoundaries = new Object[numberOfChannels - 1][];
+ for (int i = 0; i < numberOfChannels - 1; i++) {
+ this.partitionBoundaries[i] = this.distribution.getBucketBoundary(i, numberOfChannels);
+ }
+ }
+
+ if (numberOfChannels == this.partitionBoundaries.length + 1) {
+ final Object[][] boundaries = this.partitionBoundaries;
+
+ // bin search the bucket
+ int low = 0;
+ int high = this.partitionBoundaries.length - 1;
+
+ while (low <= high) {
+ final int mid = (low + high) >>> 1;
+ final int result = compareRecordAndBoundary(record, boundaries[mid]);
+
+ if (result > 0) {
+ low = mid + 1;
+ } else if (result < 0) {
+ high = mid - 1;
+ } else {
+ this.channels[0] = mid;
+ return this.channels;
+ }
+ }
+ this.channels[0] = low; // key not found, but the low index is the target
+ // bucket, since the boundaries are the upper bound
+ return this.channels;
+ } else {
+ throw new IllegalStateException(
+ "The number of channels to partition among is inconsistent with the partitioners state.");
+ }
+ }
+
private int[] customPartition(T record, int numberOfChannels) {
+ if (channels == null) {
+ channels = new int[1];
+ extractedKeys = new Object[1];
+ }
+
try {
if (comparator.extractKeys(record, extractedKeys, 0) == 1) {
final Object key = extractedKeys[0];
@@ -218,4 +281,20 @@ public class OutputEmitter<T> implements ChannelSelector<SerializationDelegate<T
throw new RuntimeException("Error while calling custom partitioner.", t);
}
}
+
+ private final int compareRecordAndBoundary(T record, Object[] boundary) {
+ this.comparator.extractKeys(record, keys, 0);
+
+ if (flatComparators.length != keys.length || flatComparators.length != boundary.length) {
+ throw new RuntimeException("Can not compare keys with boundary due to mismatched length.");
+ }
+
+ for (int i=0; i<flatComparators.length; i++) {
+ int result = flatComparators[i].compare(keys[i], boundary[i]);
+ if (result != 0) {
+ return result;
+ }
+ }
+ return 0;
+ }
}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/AssignRangeIndex.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/AssignRangeIndex.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/AssignRangeIndex.java
new file mode 100644
index 0000000..18470cf
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/AssignRangeIndex.java
@@ -0,0 +1,61 @@
+/*
+ * 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.runtime.operators.udf;
+
+import org.apache.flink.api.common.distributions.CommonRangeBoundaries;
+import org.apache.flink.api.common.distributions.RangeBoundaries;
+import org.apache.flink.api.common.functions.RichMapPartitionFunction;
+import org.apache.flink.api.common.typeutils.TypeComparatorFactory;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.util.Collector;
+
+import java.util.List;
+
+/**
+ * This mapPartition function require a DataSet with RangeBoundaries as broadcast input, it
+ * generate Tuple2 which includes range index and record itself as output.
+ *
+ * @param <IN> The original data type.
+ */
+public class AssignRangeIndex<IN> extends RichMapPartitionFunction<IN, Tuple2<Integer, IN>> {
+
+ private TypeComparatorFactory<IN> typeComparator;
+
+ public AssignRangeIndex(TypeComparatorFactory<IN> typeComparator) {
+ this.typeComparator = typeComparator;
+ }
+
+ @Override
+ public void mapPartition(Iterable<IN> values, Collector<Tuple2<Integer, IN>> out) throws Exception {
+
+ List<Object> broadcastVariable = getRuntimeContext().getBroadcastVariable("RangeBoundaries");
+ if (broadcastVariable == null || broadcastVariable.size() != 1) {
+ throw new RuntimeException("AssignRangePartition require a single RangeBoundaries as broadcast input.");
+ }
+ Object[][] boundaryObjects = (Object[][]) broadcastVariable.get(0);
+ RangeBoundaries rangeBoundaries = new CommonRangeBoundaries(typeComparator.createComparator(), boundaryObjects);
+
+ Tuple2<Integer, IN> tupleWithPartitionId = new Tuple2<>();
+
+ for (IN record : values) {
+ tupleWithPartitionId.f0 = rangeBoundaries.getRangeIndex(record);
+ tupleWithPartitionId.f1 = record;
+ out.collect(tupleWithPartitionId);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/RangeBoundaryBuilder.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/RangeBoundaryBuilder.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/RangeBoundaryBuilder.java
new file mode 100644
index 0000000..cd163d3
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/RangeBoundaryBuilder.java
@@ -0,0 +1,74 @@
+/*
+ * 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.runtime.operators.udf;
+
+import org.apache.flink.api.common.functions.RichMapPartitionFunction;
+import org.apache.flink.api.common.typeutils.TypeComparator;
+import org.apache.flink.api.common.typeutils.TypeComparatorFactory;
+import org.apache.flink.util.Collector;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Build RangeBoundaries with input records. First, sort the input records, and then select
+ * the boundaries with same interval.
+ *
+ * @param <T>
+ */
+public class RangeBoundaryBuilder<T> extends RichMapPartitionFunction<T, Object[][]> {
+
+ private int parallelism;
+ private final TypeComparatorFactory<T> comparatorFactory;
+
+ public RangeBoundaryBuilder(TypeComparatorFactory<T> comparator, int parallelism) {
+ this.comparatorFactory = comparator;
+ this.parallelism = parallelism;
+ }
+
+ @Override
+ public void mapPartition(Iterable<T> values, Collector<Object[][]> out) throws Exception {
+ final TypeComparator<T> comparator = this.comparatorFactory.createComparator();
+ List<T> sampledData = new ArrayList<>();
+ for (T value : values) {
+ sampledData.add(value);
+ }
+ Collections.sort(sampledData, new Comparator<T>() {
+ @Override
+ public int compare(T first, T second) {
+ return comparator.compare(first, second);
+ }
+ });
+
+
+ int boundarySize = parallelism - 1;
+ Object[][] boundaries = new Object[boundarySize][];
+ double avgRange = sampledData.size() / (double) parallelism;
+ int numKey = comparator.getFlatComparators().length;
+ for (int i = 1; i < parallelism; i++) {
+ T record = sampledData.get((int) (i * avgRange));
+ Object[] keys = new Object[numKey];
+ comparator.extractKeys(record, keys, 0);
+ boundaries[i-1] = keys;
+ }
+
+ out.collect(boundaries);
+ }
+}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/RemoveRangeIndex.java
----------------------------------------------------------------------
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/RemoveRangeIndex.java b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/RemoveRangeIndex.java
new file mode 100644
index 0000000..49ea893
--- /dev/null
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/operators/udf/RemoveRangeIndex.java
@@ -0,0 +1,29 @@
+/*
+ * 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.runtime.operators.udf;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.java.tuple.Tuple2;
+
+public class RemoveRangeIndex<T> implements MapFunction<Tuple2<Integer,T>,T> {
+
+ @Override
+ public T map(Tuple2<Integer, T> value) throws Exception {
+ return value.f1;
+ }
+}
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-scala/src/main/scala/org/apache/flink/api/scala/DataSet.scala
----------------------------------------------------------------------
diff --git a/flink-scala/src/main/scala/org/apache/flink/api/scala/DataSet.scala b/flink-scala/src/main/scala/org/apache/flink/api/scala/DataSet.scala
index 350a86f..a3ce53c 100644
--- a/flink-scala/src/main/scala/org/apache/flink/api/scala/DataSet.scala
+++ b/flink-scala/src/main/scala/org/apache/flink/api/scala/DataSet.scala
@@ -1349,6 +1349,62 @@ class DataSet[T: ClassTag](set: JavaDataSet[T]) {
getCallLocationName())
wrap(op)
}
+
+ /**
+ * Range-partitions a DataSet on the specified tuple field positions.
+ *
+ * '''important:''' This operation requires an extra pass over the DataSet to compute the range
+ * boundaries and shuffles the whole DataSet over the network.
+ * This can take significant amount of time.
+ *
+ */
+ def partitionByRange(fields: Int*): DataSet[T] = {
+ val op = new PartitionOperator[T](
+ javaSet,
+ PartitionMethod.RANGE,
+ new Keys.ExpressionKeys[T](fields.toArray, javaSet.getType, false),
+ getCallLocationName())
+ wrap(op)
+ }
+
+ /**
+ * Range-partitions a DataSet on the specified fields.
+ *
+ '''important:''' This operation requires an extra pass over the DataSet to compute the range
+ * boundaries and shuffles the whole DataSet over the network.
+ * This can take significant amount of time.
+ */
+ def partitionByRange(firstField: String, otherFields: String*): DataSet[T] = {
+ val op = new PartitionOperator[T](
+ javaSet,
+ PartitionMethod.RANGE,
+ new Keys.ExpressionKeys[T](firstField +: otherFields.toArray, javaSet.getType),
+ getCallLocationName())
+ wrap(op)
+ }
+
+ /**
+ * Range-partitions a DataSet using the specified key selector function.
+ *
+ '''important:''' This operation requires an extra pass over the DataSet to compute the range
+ * boundaries and shuffles the whole DataSet over the network.
+ * This can take significant amount of time.
+ */
+ def partitionByRange[K: TypeInformation](fun: T => K): DataSet[T] = {
+ val keyExtractor = new KeySelector[T, K] {
+ val cleanFun = clean(fun)
+ def getKey(in: T) = cleanFun(in)
+ }
+ val op = new PartitionOperator[T](
+ javaSet,
+ PartitionMethod.RANGE,
+ new Keys.SelectorFunctionKeys[T, K](
+ keyExtractor,
+ javaSet.getType,
+ implicitly[TypeInformation[K]]),
+ getCallLocationName())
+ wrap(op)
+ }
/**
* Partitions a tuple DataSet on the specified key fields using a custom partitioner.
http://git-wip-us.apache.org/repos/asf/flink/blob/f5957ce3/flink-tests/src/test/java/org/apache/flink/test/javaApiOperators/PartitionITCase.java
----------------------------------------------------------------------
diff --git a/flink-tests/src/test/java/org/apache/flink/test/javaApiOperators/PartitionITCase.java b/flink-tests/src/test/java/org/apache/flink/test/javaApiOperators/PartitionITCase.java
index c231eac..693dda4 100644
--- a/flink-tests/src/test/java/org/apache/flink/test/javaApiOperators/PartitionITCase.java
+++ b/flink-tests/src/test/java/org/apache/flink/test/javaApiOperators/PartitionITCase.java
@@ -18,6 +18,8 @@
package org.apache.flink.test.javaApiOperators;
+import java.util.Collections;
+import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
@@ -29,6 +31,8 @@ import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.api.java.operators.AggregateOperator;
+import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.test.javaApiOperators.util.CollectionDataSets;
@@ -39,7 +43,11 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
@RunWith(Parameterized.class)
+@SuppressWarnings("serial")
public class PartitionITCase extends MultipleProgramsTestBase {
public PartitionITCase(TestExecutionMode mode){
@@ -71,6 +79,88 @@ public class PartitionITCase extends MultipleProgramsTestBase {
}
@Test
+ public void testRangePartitionByKeyField() throws Exception {
+ /*
+ * Test range partition by key field
+ */
+
+ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+
+ DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
+ DataSet<Long> uniqLongs = ds
+ .partitionByRange(1)
+ .mapPartition(new UniqueLongMapper());
+ List<Long> result = uniqLongs.collect();
+
+ String expected = "1\n" +
+ "2\n" +
+ "3\n" +
+ "4\n" +
+ "5\n" +
+ "6\n";
+
+ compareResultAsText(result, expected);
+ }
+
+ @Test
+ public void testHashPartitionByKeyField2() throws Exception {
+ /*
+ * Test hash partition by key field
+ */
+
+ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+
+ DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
+ AggregateOperator<Tuple3<Integer, Long, String>> sum = ds
+ .map(new PrefixMapper())
+ .partitionByHash(1, 2)
+ .groupBy(1, 2)
+ .sum(0);
+
+ List<Tuple3<Integer, Long, String>> result = sum.collect();
+
+ String expected = "(1,1,Hi)\n" +
+ "(5,2,Hello)\n" +
+ "(4,3,Hello)\n" +
+ "(5,3,I am )\n" +
+ "(6,3,Luke )\n" +
+ "(34,4,Comme)\n" +
+ "(65,5,Comme)\n" +
+ "(111,6,Comme)";
+
+ compareResultAsText(result, expected);
+ }
+
+ @Test
+ public void testRangePartitionByKeyField2() throws Exception {
+ /*
+ * Test range partition by key field
+ */
+
+ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+
+ DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
+ AggregateOperator<Tuple3<Integer, Long, String>> sum = ds
+ .map(new PrefixMapper())
+ .partitionByRange(1, 2)
+ .groupBy(1, 2)
+ .sum(0);
+
+ List<Tuple3<Integer, Long, String>> result = sum.collect();
+
+ String expected = "(1,1,Hi)\n" +
+ "(5,2,Hello)\n" +
+ "(4,3,Hello)\n" +
+ "(5,3,I am )\n" +
+ "(6,3,Luke )\n" +
+ "(34,4,Comme)\n" +
+ "(65,5,Comme)\n" +
+ "(111,6,Comme)";
+
+ compareResultAsText(result, expected);
+ }
+
+ @Test
public void testHashPartitionByKeySelector() throws Exception {
/*
* Test hash partition by key selector
@@ -94,6 +184,40 @@ public class PartitionITCase extends MultipleProgramsTestBase {
compareResultAsText(result, expected);
}
+ private static class PrefixMapper implements MapFunction<Tuple3<Integer, Long, String>, Tuple3<Integer, Long, String>> {
+ @Override
+ public Tuple3<Integer, Long, String> map(Tuple3<Integer, Long, String> value) throws Exception {
+ if (value.f2.length() > 5) {
+ value.f2 = value.f2.substring(0, 5);
+ }
+ return value;
+ }
+ }
+
+ @Test
+ public void testRangePartitionByKeySelector() throws Exception {
+ /*
+ * Test range partition by key selector
+ */
+
+ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+
+ DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
+ DataSet<Long> uniqLongs = ds
+ .partitionByRange(new KeySelector1())
+ .mapPartition(new UniqueLongMapper());
+ List<Long> result = uniqLongs.collect();
+
+ String expected = "1\n" +
+ "2\n" +
+ "3\n" +
+ "4\n" +
+ "5\n" +
+ "6\n";
+
+ compareResultAsText(result, expected);
+ }
+
public static class KeySelector1 implements KeySelector<Tuple3<Integer,Long,String>, Long> {
private static final long serialVersionUID = 1L;
@@ -143,11 +267,7 @@ public class PartitionITCase extends MultipleProgramsTestBase {
@Override
public boolean filter(Long value) throws Exception {
- if (value <= 780) {
- return false;
- } else {
- return true;
- }
+ return value > 780;
}
}
@@ -156,7 +276,7 @@ public class PartitionITCase extends MultipleProgramsTestBase {
@Override
public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> v1, Tuple2<Integer, Integer> v2) {
- return new Tuple2<Integer, Integer>(v1.f0, v1.f1+v2.f1);
+ return new Tuple2<>(v1.f0, v1.f1+v2.f1);
}
}
@@ -198,6 +318,31 @@ public class PartitionITCase extends MultipleProgramsTestBase {
}
@Test
+ public void testRangePartitionByKeyFieldAndDifferentParallelism() throws Exception {
+ /*
+ * Test range partition by key field and different parallelism
+ */
+
+ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+ env.setParallelism(3);
+
+ DataSet<Tuple3<Integer, Long, String>> ds = CollectionDataSets.get3TupleDataSet(env);
+ DataSet<Long> uniqLongs = ds
+ .partitionByRange(1).setParallelism(4)
+ .mapPartition(new UniqueLongMapper());
+ List<Long> result = uniqLongs.collect();
+
+ String expected = "1\n" +
+ "2\n" +
+ "3\n" +
+ "4\n" +
+ "5\n" +
+ "6\n";
+
+ compareResultAsText(result, expected);
+ }
+
+ @Test
public void testHashPartitionWithKeyExpression() throws Exception {
/*
* Test hash partition with key expression
@@ -219,12 +364,34 @@ public class PartitionITCase extends MultipleProgramsTestBase {
compareResultAsText(result, expected);
}
+ @Test
+ public void testRangePartitionWithKeyExpression() throws Exception {
+ /*
+ * Test range partition with key expression
+ */
+
+ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+ env.setParallelism(3);
+
+ DataSet<POJO> ds = CollectionDataSets.getDuplicatePojoDataSet(env);
+ DataSet<Long> uniqLongs = ds
+ .partitionByRange("nestedPojo.longNumber").setParallelism(4)
+ .mapPartition(new UniqueNestedPojoLongMapper());
+ List<Long> result = uniqLongs.collect();
+
+ String expected = "10000\n" +
+ "20000\n" +
+ "30000\n";
+
+ compareResultAsText(result, expected);
+ }
+
public static class UniqueLongMapper implements MapPartitionFunction<Tuple3<Integer,Long,String>, Long> {
private static final long serialVersionUID = 1L;
@Override
public void mapPartition(Iterable<Tuple3<Integer, Long, String>> records, Collector<Long> out) throws Exception {
- HashSet<Long> uniq = new HashSet<Long>();
+ HashSet<Long> uniq = new HashSet<>();
for(Tuple3<Integer,Long,String> t : records) {
uniq.add(t.f1);
}
@@ -239,7 +406,7 @@ public class PartitionITCase extends MultipleProgramsTestBase {
@Override
public void mapPartition(Iterable<POJO> records, Collector<Long> out) throws Exception {
- HashSet<Long> uniq = new HashSet<Long>();
+ HashSet<Long> uniq = new HashSet<>();
for(POJO t : records) {
uniq.add(t.nestedPojo.longNumber);
}
@@ -254,7 +421,81 @@ public class PartitionITCase extends MultipleProgramsTestBase {
@Override
public Tuple2<Integer, Integer> map(Long value) throws Exception {
- return new Tuple2<Integer, Integer>(this.getRuntimeContext().getIndexOfThisSubtask(), 1);
+ return new Tuple2<>(this.getRuntimeContext().getIndexOfThisSubtask(), 1);
+ }
+ }
+
+ @Test
+ public void testRangePartitionerOnSequenceData() throws Exception {
+ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
+ DataSource<Long> dataSource = env.generateSequence(0, 10000);
+ KeySelector<Long, Long> keyExtractor = new ObjectSelfKeySelector();
+
+ MapPartitionFunction<Long, Tuple2<Long, Long>> MinMaxSelector = new MinMaxSelector();
+
+ Comparator<Tuple2<Long, Long>> tuple2Comparator = new Tuple2Comparator();
+
+ List<Tuple2<Long, Long>> collected = dataSource.partitionByRange(keyExtractor).mapPartition(MinMaxSelector).collect();
+ Collections.sort(collected, tuple2Comparator);
+
+ long previousMax = -1;
+ for (Tuple2<Long, Long> tuple2 : collected) {
+ if (previousMax == -1) {
+ previousMax = tuple2.f1;
+ } else {
+ long currentMin = tuple2.f0;
+ assertTrue(tuple2.f0 < tuple2.f1);
+ assertEquals(previousMax + 1, currentMin);
+ previousMax = tuple2.f1;
+ }
}
}
+
+ private static class ObjectSelfKeySelector implements KeySelector<Long, Long> {
+ @Override
+ public Long getKey(Long value) throws Exception {
+ return value;
+ }
+ }
+
+ private static class MinMaxSelector implements MapPartitionFunction<Long, Tuple2<Long, Long>> {
+ @Override
+ public void mapPartition(Iterable<Long> values, Collector<Tuple2<Long, Long>> out) throws Exception {
+ long max = Long.MIN_VALUE;
+ long min = Long.MAX_VALUE;
+ for (long value : values) {
+ if (value > max) {
+ max = value;
+ }
+
+ if (value < min) {
+ min = value;
+ }
+ }
+ Tuple2<Long, Long> result = new Tuple2<>(min, max);
+ out.collect(result);
+ }
+ }
+
+ private static class Tuple2Comparator implements Comparator<Tuple2<Long, Long>> {
+ @Override
+ public int compare(Tuple2<Long, Long> first, Tuple2<Long, Long> second) {
+ long result = first.f0 - second.f0;
+ if (result > 0) {
+ return 1;
+ } else if (result < 0) {
+ return -1;
+ }
+
+ result = first.f1 - second.f1;
+ if (result > 0) {
+ return 1;
+ } else if (result < 0) {
+ return -1;
+ }
+
+ return 0;
+ }
+ }
+
}