Spark(2.4.x)的新功能,并使用Java API(not Scala !!!)]
我有一个从CSV文件中读取的Dataset
。它具有如下所示的架构(命名列):
id (integer) | name (string) | color (string) | price (double) | enabled (boolean)
示例行:
23 | "hotmeatballsoup" | "blue" | 3.95 | true
数据集中有many(几万)行。我想使用适当的Java / Spark API编写一个表达式,该表达式可在每一行中滚动并在每行上执行以下两个操作:
null
,则默认为0.00
;然后2.55
由于我是Spark的新手,所以我不确定从哪里开始!到目前为止,我最大的尝试肯定是错误的,但是我认为这至少是一个起点:
Dataset csvData = sparkSession.read()
.format("csv")
.load(fileToLoad.getAbsolutePath());
// ??? get rows somehow
Seq<Seq<String>> csvRows = csvData.getRows(???, ???);
// now how to loop through rows???
for (Seq<String> row : csvRows) {
// how apply two operations specified above???
if (row["price"] == null) {
row["price"] = 0.00;
}
if (row["color"].equals("red")) {
row["price"] = row["price"] + 2.55;
}
}
有人可以在这里向正确的方向推动我吗?
您可以使用spark sql api实现它。空值也可以使用.fill()
中的DataFrameNaFunctions
替换为值。否则,您可以将Dataframe转换为Dataset并在.map
中执行这些步骤,但是在这种情况下sql api更好,更高效。
+---+---------------+-----+-----+-------+
| id| name|color|price|enabled|
+---+---------------+-----+-----+-------+
| 23|hotmeatballsoup| blue| 3.95| true|
| 24| abc| red| 1.0| true|
| 24| abc| red| null| true|
+---+---------------+-----+-----+-------+
在类声明之前导入sql函数:
import static org.apache.spark.sql.functions.*;
sql api:
df.select(
col("id"), col("name"), col("color"),
when(col("color").equalTo("red").and(col("price").isNotNull()), col("price").plus(2.55))
.when(col("color").equalTo("red").and(col("price").isNull()), 2.55)
.otherwise(col("price")).as("price")
,col("enabled")
).show();
或使用临时视图和SQL查询:
df.createOrReplaceTempView("df");
spark.sql("select id,name,color, case when color = 'red' and price is not null then (price + 2.55) when color = 'red' and price is null then 2.55 else price end as price, enabled from df").show();
输出:
+---+---------------+-----+-----+-------+
| id| name|color|price|enabled|
+---+---------------+-----+-----+-------+
| 23|hotmeatballsoup| blue| 3.95| true|
| 24| abc| red| 3.55| true|
| 24| abc| red| 2.55| true|
+---+---------------+-----+-----+-------+