How can I select multiple columns of dataset ds
in Spark 2.3 Java by passing a list argument?
For example, this works fine:
ds.select("col1","col2","col3").show();
However, this fails:
List<String> columns = Arrays.toList("col1","col2","col3");
ds.select(columns.toString()).show()
Using spark 2.4.0
you have to convert the List<String>
to Seq<String>
, and use selectExpr
following spark documentation.
If you want to use select
, you have to remove the first column from your list and add it as a parameter to select
.
Please find the two versions :
Suppose that you have the following .csv
file :
InvoiceNo,StockCode,Description,Quantity,InvoiceDate,UnitPrice,CustomerID,Country
536365,85123A,WHITE HANGING HEART T-LIGHT HOLDER,6,2010-12-01 08:26:00,2.55,17850.0,United Kingdom
536365,71053,WHITE METAL LANTERN,6,2010-12-01 08:26:00,3.39,17850.0,United Kingdom
536365,84406B,CREAM CUPID HEARTS COAT HANGER,8,2010-12-01 08:26:00,2.75,17850.0,United Kingdom
536365,84029G,KNITTED UNION FLAG HOT WATER BOTTLE,6,2010-12-01 08:26:00,3.39,17850.0,United Kingdom
536365,84029E,RED WOOLLY HOTTIE WHITE HEART.,6,2010-12-01 08:26:00,3.39,17850.0,United Kingdom
You can use this code to solve your issue:
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import java.util.Arrays;
import java.util.List;
import scala.collection.JavaConverters;
import scala.collection.Seq;
public class SparkJavaTest {
public static SparkSession spark = SparkSession
.builder()
.appName("JavaSparkTest")
.master("local")
.getOrCreate();
public static Seq<String> convertListToSeq(List<String> inputList) {
return JavaConverters.asScalaIteratorConverter(inputList.iterator()).asScala().toSeq();
}
public static void main(String[] args) {
Dataset<Row> ds = spark.read().option("header",true).csv("spark-file.csv");
List<String> columns = Arrays.asList("InvoiceNo","StockCode","Description");
//using selectExpr
ds.selectExpr(convertListToSeq(columns)).show(false);
//using select => this first column will be added to select
List<String> columns2 = Arrays.asList("StockCode","Description");
ds.select("InvoiceNo", convertListToSeq(columns2)).show(false);
}
}
Hope it helps :)
Either use
Dataset<Row> select(String col, scala.collection.Seq<String> cols)
as
Column column = "col1";
List<String> columns = Arrays.toList(""col2","col3");
ds.select(column, columns).show()
or
Dataset<Row> select(String col, String... cols)
as
List<Column> columns = Arrays.toList(col("col1"),col("col2"),col("col3"));
ds.select(columns);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With