![](/img/trans.png)
[英]Spark/Scala: Remove some component from a DataFrame with Array typed column
[英]Adding file names from array in dataframe column in spark scala
val hadoopConf = new Configuration()
val fs = FileSystem.get(hadoopConf)
val status = fs.listStatus(new Path("/home/Test/")).map(_.getPath().toString)
val df = spark.read.format("json").load(status : _*)
如何在df的新列中添加文件名?
我試過:
val dfWithCol = df.withColumn("filename",input_file_name())
但是它在所有列中添加了相同的文件名? 任何人都可以提出更好的方法嗎?
這是預期的行為,因為您的 json 文件中有more than one record
。
Spark 為每條記錄添加filenames
,並且您想要檢查所有唯一的文件名,然后在文件distinct
上執行distinct
操作
//to get unique filenames
df.select("filename").distinct().show()
Example:
#source data
hadoop fs -cat /user/shu/json/*.json
{"id":1,"name":"a"}
{"id":1,"name":"a"}
val hadoopConf = new Configuration()
val fs = FileSystem.get(hadoopConf)
val status = fs.listStatus(new Path("/user/shu/json")).map(_.getPath().toString)
val df = spark.read.format("json").load(status : _*)
df.withColumn("filename",input_file_name()).show(false)
//unique filenames for each record
+---+----+----------------------------------------------------------------------------+
|id |name|input |
+---+----+----------------------------------------------------------------------------+
|1 |a |hdfs://nn:8020/user/shu/json/i.json |
|1 |a |hdfs://nn:8020/user/shu/json/i1.json |
+---+----+----------------------------------------------------------------------------+
在上面的示例中,您可以看到每條記錄的unique filenames
(as i have 1 record in each json file)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.