我有一个分区的数据帧保存到hdfs中。我应该定期从kafka主题加载新数据并更新hdfs数据。数据很简单:只是在一定时间内收到的推文数量。
因此,分区Jan 18, 10 AM
的值可能为2
,我可能会从kafka接收后期数据,该数据由3条tweet组成,并在Jan 18, 10 AM
发送。因此,我需要将Jan 18, 10 AM
更新为2+3=5
的值。
我当前的解决方案不好,因为我
(我在代码中为每个步骤提供了注释。)
问题在于,存储在hdfs上的数据帧可能是1 TB,这是不可行的。
import com.jayway.jsonpath.JsonPath
import org.apache.hadoop.conf.Configuration
import org.apache.spark.sql.SparkSession
import org.apache.hadoop.fs.FileSystem
import org.apache.hadoop.fs.Path
import org.apache.spark.sql.types.{StringType, IntegerType, StructField, StructType}
//scalastyle:off
object TopicIngester {
val mySchema = new StructType(Array(
StructField("date", StringType, nullable = true),
StructField("key", StringType, nullable = true),
StructField("cnt", IntegerType, nullable = true)
))
def main(args: Array[String]): Unit = {
val spark = SparkSession.builder()
.master("local[*]") // remove this later
.appName("Ingester")
.getOrCreate()
import spark.implicits._
import org.apache.spark.sql.functions.count
// read the old one
val old = spark.read
.schema(mySchema)
.format("csv")
.load("/user/maria_dev/test")
// remove it
val fs = FileSystem.get(new Configuration)
val outPutPath = "/user/maria_dev/test"
if (fs.exists(new Path(outPutPath))) {
fs.delete(new Path(outPutPath), true)
}
// read the new one
val _new = spark.read
.format("kafka")
.option("kafka.bootstrap.servers", "sandbox-hdp.hortonworks.com:6667")
.option("subscribe", "test1")
.option("startingOffsets", "earliest")
.option("endingOffsets", "latest")
.load()
.selectExpr("CAST(value AS String)")
.as[String]
.map(value => transformIntoObject(value))
.map(tweet => (tweet.tweet, tweet.key, tweet.date))
.toDF("tweet", "key", "date")
.groupBy("date", "key")
.agg(count("*").alias("cnt"))
// combine the old one with the new one and write to hdfs
_new.union(old)
.groupBy("date", "key")
.agg(sum("sum").alias("cnt"))
.write.partitionBy("date", "key")
.csv("/user/maria_dev/test")
spark.stop()
}
def transformIntoObject(tweet: String): TweetWithKeys = {
val date = extractDate(tweet)
val hashTags = extractHashtags(tweet)
val tagString = String.join(",", hashTags)
TweetWithKeys(tweet, date, tagString)
}
def extractHashtags(str: String): java.util.List[String] = {
JsonPath.parse(str).read("$.entities.hashtags[*].text")
}
def extractDate(str: String): String = {
JsonPath.parse(str).read("$.created_at")
}
final case class TweetWithKeys(tweet: String, date: String, key: String)
}
如何仅加载必要的分区并更有效地更新它们?