使用Java在Apache Spark中复制数据集中的一行n次
作者:互联网
我试图从数据集中复制一行n次并从中创建一个新的数据集.但是,在复制时我需要为每个复制更改列的值,因为它最终会在最终存储时作为主键.
以下是来自SO post:Replicate Spark Row N-times的Scala代码
import org.apache.spark.sql.functions._
val result = singleRowDF
.withColumn("dummy", explode(array((1 until 100).map(lit): _*)))
.selectExpr(singleRowDF.columns: _*)
如何从Java中的值数组创建列并将其传递给explode函数?建议很有帮助.
谢谢
解决方法:
这是从数据集中复制单行n次的Java程序.
import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.explode;
import static org.apache.spark.sql.functions.lit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
public class SparkSample{
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("SparkSample")
.master("local[*]")
.getOrCreate();
//Create Dataset
List<Tuple2<String,Double>> inputList = new ArrayList<Tuple2<String,Double>>();
inputList.add(new Tuple2<String,Double>("A",1.0));
Dataset<Row> df = spark.createDataset(inputList, Encoders.tuple(Encoders.STRING(), Encoders.DOUBLE())).toDF();
df.show(false);
//Java 8 style of creating Array. You can create by using for loop as well
int[] array = IntStream.range(0, 5).toArray();
//With Dummy Column
Dataset<Row> df1 = df.withColumn("dummy", explode(lit(array)));
df1.show(false);
//Drop Dummy Column
Dataset<Row> df2 = df1.drop(col("dummy"));
df2.show(false);
}
}
以下是该计划的输出.
+---+---+
|_1 |_2 |
+---+---+
|A |1.0|
+---+---+
+---+---+-----+
|_1 |_2 |dummy|
+---+---+-----+
|A |1.0|0 |
|A |1.0|1 |
|A |1.0|2 |
|A |1.0|3 |
|A |1.0|4 |
+---+---+-----+
+---+---+
|_1 |_2 |
+---+---+
|A |1.0|
|A |1.0|
|A |1.0|
|A |1.0|
|A |1.0|
+---+---+
标签:java,apache-spark,spark-dataframe,apache-spark-dataset 来源: https://codeday.me/bug/20190701/1348832.html