加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 根据列值对spark数据帧进行分区?

发布时间:2020-12-16 09:56:01 所属栏目:安全 来源:网络整理
导读:我有一个来自sql源的数据框,如下所示: User(id: Long,fname: String,lname: String,country: String)[1,Fname1,Lname1,Belarus][2,Fname2,Lname2,Belgium][3,Fname3,Lname3,Austria][4,Fname4,Lname4,Australia] 我想将这些数据分区并写入csv文件,其中每个
我有一个来自sql源的数据框,如下所示:

User(id: Long,fname: String,lname: String,country: String)

[1,Fname1,Lname1,Belarus]
[2,Fname2,Lname2,Belgium]
[3,Fname3,Lname3,Austria]
[4,Fname4,Lname4,Australia]

我想将这些数据分区并写入csv文件,其中每个分区都基于该国家的首字母,因此白俄罗斯和比利时应该是输出文件中的一个,奥地利和澳大利亚.

解决方法

这是你可以做的

import org.apache.spark.sql.functions._
//create a dataframe with demo data
val df = spark.sparkContext.parallelize(Seq(
  (1,"Fname1","Lname1","Belarus"),(2,"Fname2","Lname2","Belgium"),(3,"Fname3","Lname3","Austria"),(4,"Fname4","Lname4","Australia")
)).toDF("id","fname","lname","country")

//create a new column with the first letter of column
val result = df.withColumn("countryFirst",split($"country","")(0))

//save the data with partitionby first letter of country 

result.write.partitionBy("countryFirst").format("com.databricks.spark.csv").save("outputpath")

编辑:
你也可以使用子串,它可以提高Raphel建议的性能

substring(Column str,int pos,int len) Substring starts at pos and is
of length len when str is String type or returns the slice of byte
array that starts at pos in byte and is of length len when str is
Binary type

val result = df.withColumn("firstCountry",substring($"country",1,1))

然后使用partitionby和write

希望这能解决你的问题!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读