【问题标题】:How to access file paths in records from Kafka and create Datasets from?如何从 Kafka 访问记录中的文件路径并从中创建数据集?
【发布时间】:2018-03-07 11:22:34
【问题描述】:

我正在使用 Java。

我正在通过 Kafka 消息接收文件路径。我需要将此文件加载到 spark RDD 中,对其进行处理,然后将其转储到 HDFS 中。

我能够从 Kafka 消息中检索文件路径。我希望在这个文件上创建一个数据集/RDD。

我无法在 Kafka 消息数据集上运行地图功能。 NPE 出错,因为 sparkContext 在 worker 上不可用。

我无法在 Kafka 消息数据集上运行 foreach。它出错并显示消息:

Queries with streaming sources must be executed with writeStream.start();" 

我不能 collect 从 kafka 消息数据集接收到的数据,因为它会出现消息错误

Queries with streaming sources must be executed with writeStream.start();;

我想这一定是一个非常普遍的用例,并且必须在很多设置中运行。

如何从我在 Kafka 消息中收到的路径将文件加载为 RDD?

SparkSession spark = SparkSession.builder()
.appName("MyKafkaStreamReader")
    .master("local[4]")
.config("spark.executor.memory", "2g")
.getOrCreate();

// Create DataSet representing the stream of input lines from kafka
Dataset<String> kafkaValues = spark.readStream()
.format("kafka")
    .option("spark.streaming.receiver.writeAheadLog.enable", true)
    .option("kafka.bootstrap.servers", Configuration.KAFKA_BROKER)
    .option("subscribe", Configuration.KAFKA_TOPIC)
    .option("fetchOffset.retryIntervalMs", 100)
    .option("checkpointLocation", "file:///tmp/checkpoint")
.load()
    .selectExpr("CAST(value AS STRING)").as(Encoders.STRING());

Dataset<String> messages = kafkaValues.map(x -> {
  ObjectMapper mapper = new ObjectMapper();
  String m = mapper.readValue(x.getBytes(), String.class);
  return m;
}, Encoders.STRING() );

// ====================
// TEST 1 : FAILS
// ====================    
// CODE TRYING TO execute MAP on the received RDD 
// This fails with a Null pointer exception because "spark" is not available on worker node

/*
Dataset<String> statusRDD = messages.map(message -> {

  // BELOW STATEMENT FAILS
  Dataset<Row> fileDataset = spark.read().option("header", "true").csv(message); 
  Dataset<Row> dedupedFileDataset = fileDataset.dropDuplicates();
  dedupedFileDataset.rdd().saveAsTextFile(getHdfsLocation());
  return getHdfsLocation();

}, Encoders.STRING());

  StreamingQuery query2 = statusRDD.writeStream().outputMode("append").format("console").start();
  */

// ====================    
// TEST 2 : FAILS
// ====================    
// CODE BELOW FAILS WITH EXCEPTION 
// "Queries with streaming sources must be executed with writeStream.start();;"
// Hence, processing the deduplication on the worker side using
/*
JavaRDD<String> messageRDD = messages.toJavaRDD();

messageRDD.foreach( message -> {

  Dataset<Row> fileDataset = spark.read().option("header", "true").csv(message);
  Dataset<Row> dedupedFileDataset = fileDataset.dropDuplicates();
  dedupedFileDataset.rdd().saveAsTextFile(getHdfsLocation());

});
*/

// ====================    
// TEST 3 : FAILS
// ====================
// CODE TRYING TO COLLECT ALSO FAILS WITH EXCEPTION
// "Queries with streaming sources must be executed with writeStream.start();;"
// List<String> mess = messages.collectAsList();

关于如何读取创建文件路径并在文件上创建 RDD 的任何想法?

【问题讨论】:

  • 我认为您无法使用结构化流实现此用例。将 Spark Streaming 与 Direct kafka 消费者一起使用。您可以在通用 foreachRDD 操作中实现自定义文件加载逻辑。

标签: java apache-spark apache-kafka spark-structured-streaming


【解决方案1】:

在结构化流中,我认为没有办法将一个流中的数据具体化为数据集操作的参数。

在 Spark 生态系统中,这可以通过结合 Spark Streaming 和 Spark SQL(数据集)来实现。我们可以使用 Spark Streaming 消费 Kafka 主题,然后使用 Spark SQL 加载相应的数据并应用所需的流程。

这样的工作大致如下:(这是在 Scala 中,Java 代码将遵循相同的结构。只是实际代码更冗长)

// configure and create spark Session

val spark = SparkSession
    .builder
    .config(...)
    .getOrCreate()

// create streaming context with a 30-second interval - adjust as required
val streamingContext = new StreamingContext(spark.sparkContext, Seconds(30))

// this uses Kafka080 client. Kafka010 has some subscription differences

val kafkaParams = Map[String, String](
  "metadata.broker.list" -> kafkaBootstrapServer,
  "group.id" -> "job-group-id",
  "auto.offset.reset" -> "largest",
  "enable.auto.commit" -> (false: java.lang.Boolean).toString
)

// create a kafka direct stream
val topics = Set("topic")
val stream = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](
     streamingContext, kafkaParams, topics)

// extract the values from the kafka message
val dataStream = stream.map{case (id, data) => data}     

// process the data
dataStream.foreachRDD { dataRDD => 
  // get all data received in the current interval
  // We are assuming that this data fits in memory. 
  // We're not processing a million files per second, are we?
  val files = dataRDD.collect()
  files.foreach{ file => 
    // this is the process proposed in the question --
    // notice how we have access to the spark session in the context of the foreachRDD
    val fileDataset = spark.read().option("header", "true").csv(file) 
    val dedupedFileDataset = fileDataset.dropDuplicates()
    // this can probably be written in terms of the dataset api
    //dedupedFileDataset.rdd().saveAsTextFile(getHdfsLocation());
    dedupedFileDataset.write.format("text").mode("overwrite").save(getHdfsLocation())
  }
}

// start the streaming process
streamingContext.start()
streamingContext.awaitTermination()

【讨论】:

  • 我遇到了类似的问题,这期间是否发生了变化,或者即使在今天,解决方案也仍然如此?
  • @Stefn 在结构化流中对流进行具体化是不可能的。您可以做的是使用新的foreachBatch 函数以与此处所示类似的方式加载数据,然后将该数据放入可以从另一个作业中使用的中间主题,
  • 我必须实现与这个问题类似的东西。使用foreachBatch 为我解决了这个问题,我还检查了缩放,它在每个微批次中的缩放都非常好!
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 2017-06-07
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 2013-02-28
  • 2015-11-14
  • 1970-01-01
相关资源
最近更新 更多