首页 > 解决方案 > 使用scala在Spark sql Dataframe中读取不明确的列名

问题描述

我在文本文件中有重复的列,当我尝试使用 spark scala 代码加载该文本文件时,它成功加载到数据框中,我可以通过 df.Show() 看到前 20 行

完整代码:-

 val sc = new SparkContext(conf)
 val hivesql = new org.apache.spark.sql.hive.HiveContext(sc)
 val rdd = sc.textFile("/...FilePath.../*")
 val fieldCount = rdd.map(_.split("[|]")).map(x => x.size).first()
 val field = rdd.zipWithIndex.filter(_._2==0).map(_._1).first()
 val fields = field.split("[|]").map(fieldName =>StructField(fieldName, StringType, nullable=true))
 val schema = StructType(fields)
 val rowRDD = rdd.map(_.split("[|]")).map(attributes => getARow(attributes,fieldCount))

val df = hivesql.createDataFrame(rowRDD, schema)
df.registerTempTable("Sample_File")
df.Show()

到目前为止,我的代码工作正常。但是一旦我尝试下面的代码,它就会给我错误。

val results = hivesql.sql("Select id,sequence,sequence from Sample_File")

所以我在文本文件中有 2 个具有相同名称的列,即序列如何访问这两个列.. 我尝试使用序列#2 但仍然无法工作 Spark 版本:-1.6.0 Scala 版本:- 2.10.5

result of df.printschema()
|-- id: string (nullable = true)
|-- sequence: string (nullable = true)
|-- sequence: string (nullable = true)

标签: scaladataframeapache-spark

解决方案


以下代码可能会帮助您解决问题。我在 Spark 1.6.3 中对此进行了测试。

val sc = new SparkContext(conf)
val hivesql = new org.apache.spark.sql.hive.HiveContext(sc)
val rdd = sc.textFile("/...FilePath.../*")
val fieldCount = rdd.map(_.split("[|]")).map(x => x.size).first()
val field = rdd.zipWithIndex.filter(_._2==0).map(_._1).first()
val fields = field.split("[|]").map(fieldName =>StructField(fieldName, StringType, nullable=true))
val schema = StructType(fields)
val rowRDD = rdd.map(_.split("[|]")).map(attributes => getARow(attributes,fieldCount))

val df = hivesql.createDataFrame(rowRDD, schema)

val colNames = Seq("id","sequence1","sequence2")
val df1 = df.toDF(colNames: _*)

df1.registerTempTable("Sample_File")

val results = hivesql.sql("select id,sequence1,sequence2 from Sample_File")


推荐阅读