About how to create a custom org.apache.spark.sql.types.StructType schema object starting from a json file programmatically

戏子无情 提交于 2019-12-05 18:38:09
Shankar

Since you said Custom Schema, you can do something like this.

val schema = (new StructType).add("field1", StringType).add("field2", StringType)
sqlContext.read.schema(schema).json("/json/file/path").show

Also, look into this and this

You can create nested JSON Schema like below.

For example:

{
  "field1": {
    "field2": {
      "field3": "create",
      "field4": 1452121277
    }
  }
}

val schema = (new StructType)
  .add("field1", (new StructType)
    .add("field2", (new StructType)
      .add("field3", StringType)
      .add("field4", LongType)
    )
  )

Finally i found the problem.

The problem was on these lines:

val myStructType = new StructType()
myStructType.add("mySchemaStructType",mySchemaStructType)

i have to use this line:

val mySchemaStructType = DataType.fromJson(schema_json.head).asInstanceOf[StructType]

I have to cast StructType from DataType in order to get things working.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!