Spark中如何向已存在Schema新增StructFields

向已有的Schema新增StructFields

就是StructType的add方法,實際業務中需要動態向DataFrame中新增列時,可以獲取最新的配置然後動態更新Schema

/**
 * Creates a new [[StructType]] by adding a new field with no metadata.
 *
 * val struct = (new StructType)
 *   .add("a", IntegerType, true)
 *   .add("b", LongType, false)
 *   .add("c", StringType, true)
 */
def add(name: String, dataType: DataType, nullable: Boolean): StructType = {
  StructType(fields :+ StructField(name, dataType, nullable, Metadata.empty))
}

要注意的是,add方法是返回一個新的Schema,所以需要賦值給引用變量。也可以傳入StructField對應的DataType,Nullable參數

def create_schema_from_list(attr_list: List[String]): StructType = {
  // 初始化 schema 並添加第一列
  // 也可以 var schema = (new StructType)先創建一個空的Schema
  var schema = StructType(StructField(attr_list(0), StringType) :: Nil)
  // 添加餘下列
  for (i <- 1 until attr_list.length) {
    schema = schema.add(attr_list(i),StringType)
  // println("Test " + attr_list(i))
  }
  return schema
}

簡單點的寫法如下:

val str = "a,b,c"
var schema = (new StructType)
str.split(",").map(x=>{schema = schema.add(x,StringType)})

更多大數據相關Tips可以關注:https://github.com/josonle/Coding-Nowhttps://github.com/josonle/BigData-Learning

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章