我正在尝试使用Spark 2.0重命名case类数据集中的嵌套字段。下面是一个示例,我试图将"element“重命名为"address”(保持它在数据结构中的嵌套位置):
df.printSchema
//Current Output:
root
|-- companyAddresses: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- addressLine: string (nullable = true)
| | |-- addressCity: string (nullable = true)
| | |-- addressCountry: string (nullable = true)
| | |-- url: string (nullable = true)
//Desired Output:
root
|-- companyAddresses: array (nullable = true)
| |-- address: struct (containsNull = true)
| | |-- addressLine: string (nullable = true)
| | |-- addressCity: string (nullable = true)
| | |-- addressCountry: string (nullable = true)
| | |-- url: string (nullable = true)作为参考,以下内容不起作用:
df.withColumnRenamed("companyAddresses.element","companyAddresses.address")
df.withColumnRenamed("companyAddresses.element","address") 发布于 2016-08-23 00:24:46
你在这里所要求的是不可能的。companyAddresses是一个数组,而element不是一个列。它只是数组成员模式的指示器。它不能被选中,也不能重命名。
仅支持重命名父容器:
df.withColumnRenamed("companyAddresses", "foo")或通过修改模式的单个字段的名称。在简单的情况下,也可以使用struct并选择:
df.select(struct($"foo".as("bar"), $"bar".as("foo")))但显然这在这里是不适用的。
发布于 2017-04-11 22:40:59
您可以为此编写一个小的递归函数,并使用一个映射:
final JavaRDD rdd = df.toJavaRDD().map(row -> ....);
private static void flatDocument(Row input, Map<String,Object> outValues, String fqn)
{
final StructType schema = input.schema();
for (StructField field : schema.fields())
{
final String fieldName = field.name();
String key = fqn == null ? fieldName : fqn + "_" + fieldName;
Object buffer = input.getAs(fieldName);
if (field.dataType().getClass().equals(StructType.class))
{
if (buffer != null) {
flatDocument((Row) buffer, outValues, key);
}
}
else
{
outValues.put(key, buffer);
}
}
}但是您需要一个模式来将其转换回DataSet :/
https://stackoverflow.com/questions/39084167
复制相似问题