【发布时间】:2021-02-05 17:32:13
【问题描述】:
我从一个 kafka 主题中检索数据。将数据转换为具有 10 列的数据框后,我选择其中一列。我想在每一行中拆分字符串,以便将单词转换为它们的发音。 evrything 似乎没问题,但我唯一的问题是我不能连续运行 split 方法。?
这是我的代码
val df = spark.readStream.format("kafka").option("kafka.bootstrap.servers", "rocket-01.srvs.cloudkafka.com:9094")
.option("subscribe", "k-news")
.option("startingOffsets", "latest")
.option("kafka.security.protocol","SASL_SSL")
.option("kafka.sasl.mechanism", "SCRAM-SHA-256")
.option("kafka.sasl.jaas.config", "org.apache.kafka.common.security.scram.ScramLoginModule required username=" " password="";").load()
val newsStringDF = df.selectExpr("CAST(value AS STRING)")
val newsSchema = StructType( Array(
StructField("_c0",StringType,true),
StructField("id",StringType,true),
StructField("title",StringType,true),
StructField("publication",StringType,true),
StructField("author",StringType,true),
StructField("date",StringType,true),
StructField("year",StringType,true),
StructField("month",StringType,true),
StructField("url",StringType,true),
StructField("content",StringType,true)))
val lines = Source.fromFile("/Project/symbols/cmudict.dict").getLines()
val res = lines.map { line =>line.split(" ", 2) match { case Array(a, b) => a -> b }}.toMap
val newsDF = newsStringDF.select(from_json(col("value"),
newsSchema).as("data")).select("data.*")
val titleColumn = newsDF.select("title").as[String].foreach( message =>
message.split(" ").toList.map { s =>if(res.get(s).isDefined) {res(s)} else
{s}}.mkString(" ")).toDF("title")
val streaming = titleColumn.writeStream.format("console").outputMode("append").trigger(Trigger.ProcessingTime("10 seconds")).start().awaitTermination()
输出应该是这样的: 我从我的 kafka-topic 获取消息(来自标题列的字符串),然后用另一个字符串替换它。 “我喜欢足球” --> “我喜欢 ˈfo͝otˌbôl” 并使用 .writeStream 将消息写入控制台
提前致谢
【问题讨论】:
-
你能用最少的代码来重现这个吗? (包括模式定义、样本输入数据、变量
res的定义)。理想情况下,还应提供预期输出的示例。 -
最好能得到一个样本输入和输出数据集和几行代码sn-p,你必须清楚地了解问题。
-
现在我更新了我的问题并试图解释输出应该是什么样子。感谢您提前提供任何帮助。
-
你能告诉我你的 spark-submit 命令吗?我正在处理类似的问题,但我不确定如何配置 spark-submit
标签: scala apache-spark apache-spark-sql spark-streaming apache-kafka-streams