我正在使用MongoDB
作为JSON从Spark
读取数据:
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.Row;
....
..
Dataset<Row> ds = MongoSpark.load(jsc).toDF();
我需要将此DF存储到Hive。
问题在于MongoDB中的列名之一是Timestamp
,这是Hive中的保留字。
因此,来自MongoDB的JSON数据包含一个密钥timestamp
。
我需要将此json键"timestamp"
替换为"timestamp_"
。
如何将"timestamp"
中的列名Dataset<Row> ds
替换为"timestamp_"
?
答案 0 :(得分:1)
如果要重命名嵌套的列,可以执行以下操作:
假设您的数据集架构如下:
root
|-- col1
|-- col2
|-- struct1
| |-- timestamp
| |-- a
| |-- b
因此您可以执行以下操作
ds = ds
.select(col("*"), col("struct1.*"))
.withColumnRenamed("timestamp", "timestamp_")
.select(
col("col1"),
col("col2"),
struct("timestamp_", "a", "b").as("struct1")
);
如果要重命名数组中的嵌套列,则首先应使用explode
函数来扩展数组。
ds = ds.select(col("a"), col("b"), explode(col("struct1")))
然后,您可以如上所述重命名嵌套的列。重命名后,如果要将结构折叠回数组下,请使用groupBy(...).agg(collect_list(...))
。