原来代码:
finalDf.rdd.repartition(100).foreach(itm => {
val InsertOne = new Document("app", itm(0)).append("day", itm(1)).append("hour", itm(2)).append("adx", itm(3))
//单条插入:
mongoConn.withCollectionDo(new WriteConfig(databaseName,
ResultCol, Option(MongoConn)), { col: MongoCollection[Document] => col.insertOne(InsertOne) })
})
修改后:
val insertRdd = finalDf.rdd.coalesce(100).map(itm => {
val insertOne = new Document("app", itm(0)).append("day", itm(1)).append("hour", itm(2)).append("adx", itm(3))
insertOne
})
//批量写
MongoSpark.save(insertRdd)
由于是从s3上往阿里云的mongo上插入,通过ping命令,知道ping一次大概要2ms,如果单条查,每一次插入相当于一次ping,时间都花在了网络上
,另外批量插入,mongo的压力也小,如图1.为批量插入
图2位单条插入