scala - 使用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)
解决方案
以下代码可能会帮助您解决问题。我在 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")
推荐阅读
- google-sheets - 有没有办法将来自多个来源的数据与 Google 的新 BigQuery 混合?
- c++ - 如何在没有 lambda 表达式的情况下将函数传递给 boost::geometry::index::satisfies()
- java - 虽然循环无法与扫描仪一起正常工作
- image - 我可以使用 Rmd 中的变量指定文件路径吗?
- c# - C# 任务不在新线程中执行
- class - 如何编写对另一个类的状态的 puppet 类依赖
- javascript - 如何使用 axios get 方法获取 onDownloadProgress 百分比?
- java - 带有前缀的 UUID 的 Java 正则表达式
- ruby-on-rails - Rails 迁移添加了一个 null: false 列,其初始值不是持续的默认值
- ios - 是否有某种包装器可以让蓝牙与网络应用程序通信?当然使用本机构建来保存包装器