您可以通过编程方式指定架构
// The schema is encoded in a string
val schemaString = "name age"
// Import Row.
import org.apache.spark.sql.Row;
// Import Spark SQL data types
import org.apache.spark.sql.types.{StructType,StructField,StringType};
// Generate the schema based on the string of schema
val schema =
StructType(
schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, true)))
// Convert records of the RDD (people) to Rows.
val rowRDD = people.map(_.split(",")).map(p => Row(p(0), p(1).trim))
// Apply the schema to the RDD.
val peopleDataFrame = sqlContext.createDataFrame(rowRDD, schema)
请看:http://spark.apache.org/docs/latest/sql-programming-guide.html
spark-avro 然后使用模式类型来指定 avro 类型,如下所示
- Spark SQL 类型 -> Avro 类型
- ByteType -> int
- ShortType -> int
- DecimalType -> 字符串
- BinaryType -> 字节
- TimestampType -> 长
- StructType -> 记录
您可以按如下方式编写 Avro 记录:
import com.databricks.spark.avro._
val sqlContext = new SQLContext(sc)
import sqlContext.implicits._
val df = Seq((2012, 8, "Batman", 9.8),
(2012, 8, "Hero", 8.7),
(2012, 7, "Robot", 5.5),
(2011, 7, "Git", 2.0))
.toDF("year", "month", "title", "rating")
df.write.partitionBy("year", "month").avro("/tmp/output")