数据集-API模拟JavaSparkContext.wholeTextFiles [英] Dataset-API analog of JavaSparkContext.wholeTextFiles
问题描述
我们可以调用 JavaSparkContext.wholeTextFiles
并获取 JavaPairRDD< String,String>
,其中第一个String是文件名第二个String是整个文件内容。在Dataset API中是否有类似的方法,或者我所能做的就是将文件加载到 JavaPairRDD
然后转换为Dataset(这是有效的,但我正在寻找非RDD解决方案)。
We can call JavaSparkContext.wholeTextFiles
and get JavaPairRDD<String, String>
, where first String is file name and second String is whole file contents. Is there similar method in Dataset API, or all I can do is to load files into JavaPairRDD
and then convert to Dataset (which is working, but I'm looking for non-RDD solution).
推荐答案
如果您想使用数据集API,那么您可以使用 spark.read。文本( 路径/到/文件/)
。请检查此处有关API的详细信息。请注意,使用 text()
方法返回Dataframe,其中文本文件中的每一行都是生成的DataFrame中的新行。所以 text()
方法将提供文件内容。要获取文件名,您必须使用 input_file_name()
函数。
If you want to use Dataset API then you can use spark.read.text("path/to/files/")
. Please check here for API details. Please note that using text()
method returns Dataframe in which "Each line in the text files is a new row in the resulting DataFrame". So text()
method will provide file content. In order to get the file name you will have to use input_file_name()
function.
import static org.apache.spark.sql.functions.input_file_name;
Dataset<Row> ds = spark.read().text("c:\\temp").withColumnRenamed("value", "content").withColumn("fileName", input_file_name());
ds.show(false);
如果你想连接同一个文件中的行,那么就像整个文件内容一样,你需要在fileName列上使用 groupBy
函数,其中包含 concat_ws
和 collect_list
功能。
If you want to concatenate rows from same file so it will be like whole file content, you would need to use groupBy
function on fileName column with concat_ws
and collect_list
functions.
import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.concat_ws;
import static org.apache.spark.sql.functions.collect_list;
ds = ds.groupBy(col("fileName")).agg(concat_ws("",collect_list(ds.col("content"))).as("content"));
ds.show(false);
这篇关于数据集-API模拟JavaSparkContext.wholeTextFiles的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!