Spark avro to parquet

时间:2016-03-18 07:22:50

标签: scala apache-spark spark-dataframe avro parquet

我有一个avro格式的数据流(json编码),需要存储为镶木地板文件。我只能这样做,

val df = sqc.read.json(jsonRDD).toDF()

并将df写为镶木地板。

这里的模式是从json推断出来的。但我已经有了avsc文件,我不想要从json推断出模式。

以上面提到的方式,镶木地板文件将架构信息存储为StructType而不是avro.record.type。有没有办法存储avro架构信息。

SPARK - 1.4.1

2 个答案:

答案 0 :(得分:2)

结束使用此问题的答案avro-schema-to-spark-structtype

def getSparkSchemaForAvro(sqc: SQLContext, avroSchema: Schema): StructType = {
    val dummyFIle = File.createTempFile("avro_dummy", "avro")
    val datumWriter = new GenericDatumWriter[wuser]()
    datumWriter.setSchema(avroSchema)
    val writer = new DataFileWriter(datumWriter).create(avroSchema, dummyFIle)
    writer.flush()
    writer.close()
    val df = sqc.read.format("com.databricks.spark.avro").load(dummyFIle.getAbsolutePath)
    df.schema
}

答案 1 :(得分:0)

您可以通过编程方式指定架构

// 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类型
  • 字节类型 - > 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")
相关问题