Python 火花流:读取卡夫卡的CSV字符串,写入拼花地板

Python 火花流:读取卡夫卡的CSV字符串,写入拼花地板,python,csv,apache-spark,apache-kafka,spark-structured-streaming,Python,Csv,Apache Spark,Apache Kafka,Spark Structured Streaming,在线上有很多从Kafka读取json的例子(写入拼花)——但我不知道如何将模式应用于Kafka的CSV字符串 流式数据: customer_1945,cusaccid_995,27999941 customer_1459,cusaccid_1102,27999942 模式: schema = StructType() \ .add("customer_id",StringType()) \ .add("customer_acct_id",StringType()) \ .add("se

在线上有很多从Kafka读取json的例子(写入拼花)——但我不知道如何将模式应用于Kafka的CSV字符串

流式数据:

customer_1945,cusaccid_995,27999941    
customer_1459,cusaccid_1102,27999942
模式:

schema = StructType() \
.add("customer_id",StringType()) \
.add("customer_acct_id",StringType()) \
.add("serv_acct_id",StringType())
阅读流:

df = spark \
  .readStream \
  .format("kafka") \
  .option("kafka.bootstrap.servers", "xx.xx.xx.xx:9092") \
  .option("subscribe", "test") \
  .load()
我将其用于JSON:

interval=df \
  .select(from_json(col("value").cast("string"), schema).alias("json")) \
  .select("json.*")
在使用指定的模式将其写入拼花地板之前:

query=interval     \
  .writeStream  \
  .format("parquet") \
  .option("checkpointLocation", "/user/whatever/checkpoint24") \
  .start("/user/ehatever/interval24")

由于我无法将from_json()用于CSV,我不知道如何将模式应用于数据帧,以便使用类似的writeStream()命令。

我就是这样做的。在不使用from_json的情况下,提取csv字符串:

interval=df.select(col("value").cast("string")) .alias("csv").select("csv.*")
然后把它分成几列。可以使用上面相同的语句将其写入拼花地板文件

interval2=interval \
      .selectExpr("split(value,',')[0] as customer_id" \
                 ,"split(value,',')[1] as customer_acct_id" \
                 ,"split(value,',')[2] as serv_acct_id" \
                 ,"split(value,',')[3] as installed_service_id" \
                 ,"split(value,',')[4] as meter_id" \
                 ,"split(value,',')[5] as channel_number" \
                 ... etc
                 )