首页 > 解决方案 > 在 Scala 中将数据帧转换为 Map 时出现编译器错误

问题描述

我正在尝试将以下数据框:chunkMeta 转换为 scala 中的 Map:

tablename  Code
table1      432
table2      567
table3      987

scala> val dataMap = chunkMeta.select($"tablename", $"code".cast("long")).as[(String, Long)].collect.toMap

如果我打印上面的地图,我可以看到数据:

scala> dataMap.foreach(println) => (table1,432)(table2,567)(table3,987)

但是当我在 IntelliJ IDEA 上将相同的数据帧转换为 Map 时,编译器给了我一个错误:

Cannot resolve overloaded method 'select'

构建.sbt:

scalaVersion := "2.11.8"


libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "2.0.0" % "provided",
  "org.apache.spark" %% "spark-sql" % "2.0.0" % "provided",
  "org.json4s" %% "json4s-jackson" % "3.2.11" % "provided",
  "org.apache.httpcomponents" % "httpclient" % "4.5.3"
)

// https://mvnrepository.com/artifact/org.postgresql/postgresql
libraryDependencies += "org.postgresql" % "postgresql" % "42.1.4"

我不明白为什么相同的语句适用于 scala REPL 但不适用于 IntelliJ。有没有更好的方法将数据框转换为 Map ?或者这是 scala 编译器的错误?

标签: scala

解决方案


您可以使用map函数来操作数据框对象。

像下面这样的东西应该可以工作。

import spark.implicits._

val chunkMeta = Seq(("table1",432),
      ("table2",567),
      ("table3",987),
      ("table1",789)).
      toDF("tablename", "Code").toDF()

chunkMeta.show()

+---------+----+
|tablename|Code|
+---------+----+
|   table1| 432|
|   table2| 567|
|   table3| 987|
|   table1| 789|
+---------+----+

chunkMeta.printSchema()

root
 |-- tablename: string (nullable = true)
 |-- Code: integer (nullable = false)

val df2 = chunkMeta.map(r => (r.getString(0),r.getInt(1)))

df2.printSchema()

root
 |-- _1: string (nullable = true)
 |-- _2: integer (nullable = false)

val map1 = df2.collect().toMap
map1.foreach(println)

(table1,789)
(table2,567)
(table3,987)

推荐阅读