【问题标题】:required: org.apache.spark.sql.Row必需:org.apache.spark.sql.Row
【发布时间】:2018-04-21 23:04:40
【问题描述】:

我在尝试将 spark 数据帧的一列从十六进制字符串转换为双精度时遇到问题。我有以下代码:

import spark.implicits._
case class MsgRow(block_number: Long, to: String, from: String, value: Double )

def hex2int (hex: String): Double = (new BigInteger(hex.substring(2),16)).doubleValue

txs = txs.map(row=> 
        MsgRow(row.getLong(0), row.getString(1), row.getString(2), hex2int(row.getString(3)))
)

我无法分享我的 txs 数据框的内容,但这里是元数据:

>txs
org.apache.spark.sql.DataFrame = [blockNumber: bigint, to: string ... 4 more fields]

但是当我运行它时,我得到了错误:

错误:类型不匹配; 找到:MsgRow 必需:org.apache.spark.sql.Row MsgRow(row.getLong(0), row.getString(1), row.getString(2), hex2int(row.getString(3))) ^

我不明白——为什么 spark/scala 需要一个行对象?我所见过的例子都没有涉及到行的显式转换,事实上,它们中的大多数都涉及返回案例类对象的匿名函数,就像我上面所说的那样。出于某种原因,谷歌搜索“必需:org.apache.spark.sql.Row”只返回五个结果,其中没有一个与我的情况有关。这就是为什么我把标题写得如此不具体,因为误报的可能性很小。提前致谢!

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    您的错误是因为您将输出存储到同一个变量中,而 txs 在您返回 MsgRow 时期待 Row。如此变化

    txs = txs.map(row=> 
            MsgRow(row.getLong(0), row.getString(1), row.getString(2), hex2int(row.getString(3)))
    )
    

    val newTxs = txs.map(row=>
      MsgRow(row.getLong(0), row.getString(1), row.getString(2), (new BigInteger(row.getString(3).substring(2),16)).doubleValue)
    )
    

    应该可以解决您的问题。

    我已经排除了 hex2int 函数作为它的序列化错误。

    【讨论】:

    • 啊,我明白了。我没有意识到实际的行需要是相同的类型才能覆盖数据帧 var。我认为更根本的问题(见解决方案)是从地图返回的结果是一个数据集,而不是一个数据框。
    【解决方案2】:

    感谢@Ramesh 指出我的代码中的错误。他的解决方案有效,尽管它也没有提到与我的 OP 更直接相关的问题,即从 map 返回的结果不是数据帧而是数据集。而不是创建一个新变量,我需要做的就是改变

    txs = txs.map(row=> 
        MsgRow(row.getLong(0), row.getString(1), row.getString(2), hex2int(row.getString(3)))
    )
    

    txs = txs.map(row=> 
        MsgRow(row.getLong(0), row.getString(1), row.getString(2), hex2int(row.getString(3)))
    ).toDF
    

    这可能是包含我的标题的大多数错误的简单答案。虽然@Ramesh 的回答消除了该错误,但后来当我尝试将此结果连接到另一个数据帧时,我遇到了另一个错误,该错误与相同的基本问题有关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      相关资源
      最近更新 更多