0

我正在尝试使用 Spark 2.0 重命名案例类数据集中的嵌套字段。一个例子如下,我试图将“元素”重命名为“地址”(保持它在数据结构中的嵌套位置):

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") 
4

2 回答 2

1

你在这里要求的是不可能的。companyAddresses是一个数组,element根本不是一列。它只是数组成员模式的指示符。它不能被选中,也不能被重命名。

您只能重命名父容器:

df.withColumnRenamed("companyAddresses", "foo")

或通过修改架构的各个字段的名称。在简单的情况下,也可以使用struct和选择:

df.select(struct($"foo".as("bar"), $"bar".as("foo")))

但显然这在这里不适用。

于 2016-08-22T16:24:45.643 回答
0

您可以为此编写一个小型递归函数,并使用映射:

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 :/

于 2017-04-11T14:40:59.480 回答