[英]Creating Spark SQL's StructType: use add method or a constructor?
我正在從另一個自定義Java類的模式創建一個StructType
,我可以從中提取列名和數據類型。
據我所知,似乎有兩種方法來構造StructType:
我基本上可以使用這兩種方法,因為我遍歷我的自定義模式類來逐個提取字段。 問題是,似乎add
方法每次調用時都會創建一個新的StructType,這似乎是不必要的復雜處理方式,所以我實際上想知道每次調用它是否真的會創建一個新對象。 如果沒有,我認為add
是比創建StructField
的新ArrayList更好的方法
如果檢查StructType類的源代碼,您將看到add方法使用new StructField
調用StructType
構造函數,因此它將創建新的StructType。
def add(name: String, dataType: DataType): StructType = {
StructType(fields :+ new StructField(name, dataType, nullable = true, Metadata.empty))
}
您可以使用以下示例程序進行驗證。
public class QuickTest {
public static void main(String[] args) {
SparkSession sparkSession = SparkSession
.builder()
.appName("QuickTest")
.master("local[*]")
.getOrCreate();
//StructType
StructType st1 = new StructType().add("name", DataTypes.StringType);
System.out.println("hashCode "+st1.hashCode());
System.out.println("structType "+st1.toString());
//add
st1.add("age", DataTypes.IntegerType);
System.out.println("hashCode "+st1.hashCode());
System.out.println("structType "+st1.toString());
//add and assign
StructType st2 = st1.add("age", DataTypes.IntegerType);
System.out.println("hashCode "+st2.hashCode());
System.out.println("structType "+st2.toString());
//constructor
StructType st3 = new StructType(new StructField[] {new StructField("name", DataTypes.StringType, true, null), new StructField("age", DataTypes.IntegerType, true, null)});
System.out.println("hashCode "+st3.hashCode());
System.out.println("structType "+st3.toString());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.