2016-10-04 90 views
0

我正在將bson從Mongo加載到Spark中,如here所述。它的工作原理,但我得到的是:BSONObject到DataFrame的RDD

org.apache.spark.rdd.RDD[(Object, org.bson.BSONObject)]

應該基本上只是JSON所有String領域。我的其餘代碼需要一個DataFrame對象來操作數據。但是,當然,toDF在該RDD上失敗。如何將它轉換爲Spark DataFrame,其所有字段爲String?類似於spark.read.json的東西將是非常棒的。

回答

0
val datapath = "path_to_bson_file.bson" 

import org.apache.hadoop.conf.Configuration 

// Set up the configuration for reading from bson dump. 
val bsonConfig = new Configuration() 
bsonConfig.set("mongo.job.input.format", "com.mongodb.hadoop.BSONFileInputFormat") 

// given with your spark session 
implicit lazy val sparkSession = initSpark() 

// read the RDD[org.bson.BSONObject] 
val bson_data_as_json_string = sparkSession.sparkContext.newAPIHadoopFile(datapath, 
    classOf[com.mongodb.hadoop.BSONFileInputFormat]. 
    asSubclass(classOf[org.apache.hadoop.mapreduce.lib.input.FileInputFormat[Object, org.bson.BSONObject]]), 
    classOf[Object], 
    classOf[org.bson.BSONObject], 
    bsonConfig). 
    map{row => { 
    // map BSON object to JSON string 
    val json = com.mongodb.util.JSON.serialize(row._2) 
    json 
    } 
} 

// read into JSON spark Dataset: 
val bson_data_as_json_dataset = sparkSession.sqlContext.read.json(bson_data_as_json_string) 
// eval the schema: 
bson_data_as_json_dataset.printSchema() 
相關問題