【问题标题】:How does Cassandra type cast a datatype internally when we are trying to write a Spark DataFrame into Cassandra?当我们尝试将 Spark DataFrame 写入 Cassandra 时,Cassandra 类型如何在内部转换数据类型?
【发布时间】:2019-01-08 21:26:59
【问题描述】:

为了提供更多关于这个问题的见解,当我们尝试将字符串写入 Cassandra 中的整数列时,Cassandra 如何在内部进行类型转换或将此字符串输入设想为整数?

Cassandra 架构:

CREATE TABLE keyspace_name.table_name1 (
    col1 text,
    col2 int,
    col3 text,
    col4 text PRIMARY KEY (col1)

DataFrame 架构:

root
 |-- col1: string (nullable = true)
 |-- col2: string (nullable = true)
 |-- col3: string (nullable = true)
 |-- col4: string (nullable = true)

【问题讨论】:

    标签: apache-spark cassandra apache-spark-sql spark-cassandra-connector


    【解决方案1】:

    这是通过为不同的 CQL 类型注册类型转换器来完成的。例如,在PrimitiveColumnType.scala 中为int 类型定义了以下代码:

    case object IntType extends PrimitiveColumnType[Int] {
      def scalaTypeTag = implicitly[TypeTag[Int]]
      def cqlTypeName = "int"
      def converterToCassandra =
        new TypeConverter.OptionToNullConverter(TypeConverter.forType[java.lang.Integer])
    }
    

    此代码使用通用convertimplementation,将特定类型实现的实际转换卸载到部分函数convertPF。对于能够从Number 或String 转换为整数的IntConverter:

    def convertPF = {
      case x: Number => x.intValue
      case x: String => x.toInt
    }
    

    您可以寻找其他实现,例如,CQL date 可以从不同的类型中获得 - 字符串、长整型、UUID...

    【讨论】:

    • 感谢您的更新!现在,我对此有了一些基本的了解。
    猜你喜欢
    • 2023-03-28
    • 2020-05-13
    • 1970-01-01
    • 2017-04-12
    • 2016-04-15
    • 2020-06-10
    • 2020-06-30
    • 2019-10-15
    • 2017-10-11
    相关资源
    最近更新 更多