【问题标题】:How to cast a decimal value into String in spark while reading data from Greenplum?从Greenplum读取数据时,如何在火花中将十进制值转换为字符串?
【发布时间】:2018-12-24 11:04:00
【问题描述】:

我正在尝试使用 spark 读取 Greenplum 数据库上的 RDBMS 表。我有以下列:

val allColumnsSeq: Seq[String] = Seq("usd_exchange_rate", "usd_exchange_rate::character varying as usd_exchange_rate_text")

我正在尝试将 spark 中的上述列读取为:

val yearDF = spark.read.format("io.pivotal.greenplum.spark.GreenplumRelationProvider").option("url", connectionUrl)
.option("dbtable", "x_lines")
.option("dbschema","copydb")
.option("user", devUserName).option("password", devPassword)
.option("partitionColumn","id")
.load()
.where("year=2017 and month=12")
.select(allColumnsSeq map col:_*)
.withColumn(flagCol, lit(0))

gp 中的某些列是数据类型:decimal,其中包含精度数字。 上表中为:

usd_exchange_rate

它包含近 45 位精度。在我们的项目中,我们保留原始列(usd_exchange_rate),并从字符数据类型的 usd_exchange_rate 创建一个新列,其列名附加_text。在这种情况下,

decimal datatype: usd_exchange_rate & char datatype: usd_exchange_rate_text 中的同一列

当我执行上述行时,我得到了异常:

org.apache.spark.sql.AnalysisException: cannot resolve '`usd_exchange_rate::character varying as usd_exchange_rate_text`'

我发现我将其转换为错误的格式,但我不明白如何一步读取十进制和文本格式的同一列。 谁能告诉我是否有办法在 spark 中实现它?

【问题讨论】:

  • 鉴于limitations of connector,看起来您将在源代码中创建一个视图,然后从那里读取(当然,除非您想切换到内置的 JDBC 源代码)。

标签: apache-spark greenplum


【解决方案1】:

不确定错误,但要转换,您是否尝试定义自定义架构?假设您已经知道您的架构,请使用 StructType 定义您自己的自定义架构。

import org.apache.spark.sql.types._

val customSchema = StructType(Seq(
StructField("usd_exchange_rate",StringType,true),
StructField("aud_exchange_rate",StringType,true),
.
.
.
StructField("<some field>",<data type>,<Boolean for nullable>)
))

val yearDF = spark.read.format("io.pivotal.greenplum.spark.GreenplumRelationProvider").option("url", connectionUrl)
    .option("dbtable", "x_lines")
    .option("dbschema","copydb")
    .option("user", devUserName).option("password", devPassword)
    .option("partitionColumn","id")
    .schema(customSchema)
    .load()
    .where("year=2017 and month=12")
    .select(allColumnsSeq map col:_*)
    .withColumn(flagCol, lit(0))

我没有在 IDE 中对此进行测试,但它应该可以工作。

【讨论】:

  • 这可以给我 'StructField("usd_exchange_rate",StringType,true)' 字符串数据类型的列。但我也应该有原始列及其数据类型。 Like -> 一个具有相同列名和数据类型:StructField("usd_exchange_rate",DecimalType,true),其他为 StructField("usd_exchange_rate_text",StringType,true) 我该如何给出?
猜你喜欢
  • 2017-06-16
  • 2015-02-06
  • 1970-01-01
  • 2012-09-17
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 2023-03-16
相关资源
最近更新 更多