简体   繁体   English

获取包含在 Apache spark 数据集中的列的列数据类型

[英]Get column data type of a column contained in a Apache spark data set

I am trying to find if there is a way to get the datatype of a column contained in a Apache spark data set using java?我试图找到是否有办法使用 java 获取包含在 Apache spark 数据集中的列的数据类型? I have a data set which contains a column called SSN and I wrote this code to trim the data in that column :我有一个数据集,其中包含一个名为SSN的列,我编写了此代码来修剪该列中的数据:

Dataset<Row> trimmedOutput = trimInput.select(trim(trimInput.col("SSN")).as("SSN")

I am trying to get the data type of the SSN column to validate it against the expected type.我正在尝试获取SSN列的数据类型以根据预期类型对其进行验证。

Can someone please help me?有人可以帮助我吗?

I came here looking for the same answer :) Now looking at the API, this is one way I can figure:我来这里寻找相同的答案 :) 现在查看 API,这是我能想到的一种方法:

public static String dataTypeString(Dataset<Row> dataset, String colName) {
        StructField[] fields = dataset.schema().fields();
        String dataType = null;
        for(StructField field: fields) {
            if(field.name().equals(colName)) {
                dataType =  field.dataType().typeName();
                break;
            }
        }
        return dataType;
    }

To know the datatype of the SSN column in the trimmedOutput dataset, use it like below:要了解 trimmedOutput 数据集中 SSN 列的数据类型,请使用如下所示:

dataTypeString(trimmedOutput, "SSN") 

There is also a similar method simpleString() that you can invoke instead of typeName(), API docs mention the difference between these two.还有一个类似的方法 simpleString() 可以代替 typeName() 调用,API 文档提到了这两者之间的区别。

If your intention is to check if a column in a dataset is of a certain datatype and fail if that's not the case, the below code will help:如果您的目的是检查数据集中的列是否属于某种数据类型,如果不是这种情况则失败,以下代码将有所帮助:

SchemaUtils.checkColumnType(holdoutResults.schema(), 
                            "SSN", 
                            DataTypes.StrringType, 
                           "Datatype Mismatch for column SSN");

The above invocation will check if the 'SSN' column if of type String and if not so, it will fail by showing the message that you passed as the last argument - "Datatype Mismatch for column SSN".上面的调用将检查 'SSN' 列是否为 String 类型,如果不是,它将通过显示您作为最后一个参数传递的消息 - “列 SSN 的数据类型不匹配”而失败。 This method is available only on the SchemUtils class from the ml library.此方法仅适用于 ml 库中的 SchemUtils 类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM