我有使用lowerCamelCase变量名约定的case类。 Cassandra对行和表名使用lower_underscore约定。 有没有办法指示DataFrame自动转换名称?
表格定义:
CREATE TABLE data_storage.dummy (
some_name text,
some_value text,
PRIMARY KEY (some_name)
);
Spark代码:
val ds = List(Dummy("key", 1)).toDS()
ds.write
.format("org.apache.spark.sql.cassandra")
.option("keyspace", "data_storage")
.option("table", "dummy")
.save
我写了一个函数,将名称从camel更改为下划线,反之亦然,但在某些旧案例类也使用lower_underscore命名约定的情况下,它不起作用。
private def toUnderscore(ds: DataFrame): DataFrame = {
normalizeNames(ds, CaseFormat.LOWER_CAMEL, CaseFormat.LOWER_UNDERSCORE)
}
private def toCamel(ds: DataFrame): DataFrame =
normalizeNames(ds, CaseFormat.LOWER_UNDERSCORE, CaseFormat.LOWER_CAMEL)
private def normalizeNames(df: DataFrame, from: CaseFormat, to: CaseFormat): DataFrame = {
def normalizeName(c: String): String = from.to(to, c.toString)
def flattenSchema(schema: StructType): StructType = {
StructType(schema.fields.map {
case StructField(name, inner: StructType, nullable, metadata) =>
StructField(normalizeName(name), flattenSchema(inner), nullable, metadata)
case StructField(name, array: ArrayType, nullable, metadata) =>
StructField(
normalizeName(name), array.copy(elementType = array.elementType match {
case s: StructType => flattenSchema(s)
case x => x
}), nullable, metadata)
case StructField(name, flat, nullable, metadata) =>
StructField(normalizeName(name), flat, nullable, metadata)
})
}
答案 0 :(得分:2)
此类名称转换没有内置方法。 RDD接口有一些围绕它进行类型转换的类型转换的其他方法,但通常我们没有为DataSets / DataFrames添加机制。