Spark:如何定义模式来读取不同列数的csv文件?

Spark:如何定义模式来读取不同列数的csv文件?,csv,pyspark,stream,schema,Csv,Pyspark,Stream,Schema,我正在尝试使用Pyspark读取csv文件。Csv文件有一些元信息和数据列,它们具有不同的列号和结构 Excel读取此文件没有问题。 我想在spark中定义一个自定义模式来读取此文件。 以下是一个例子: HEADER_TAG\tHEADER_VALUE FORMAT\t2.00 NUMBER_PASSES\t0001 "Time"\t"Name"\t"Country"\t"City"\t"Street"\t"Phone1"\t"Phone2" 0.49tName1\tUSA\tNewYork\t

我正在尝试使用Pyspark读取csv文件。Csv文件有一些元信息和数据列,它们具有不同的列号和结构

Excel读取此文件没有问题。 我想在spark中定义一个自定义模式来读取此文件。 以下是一个例子:

HEADER_TAG\tHEADER_VALUE
FORMAT\t2.00
NUMBER_PASSES\t0001
"Time"\t"Name"\t"Country"\t"City"\t"Street"\t"Phone1"\t"Phone2"
0.49tName1\tUSA\tNewYork\t5th Avenue\t123456\t+001236273
0.5tName2\tUSA\tWashington\t524 Street\t222222\t+0012222
0.62tName3\tGermany\tBerlin\tLinden Strasse\t3434343\t+491343434
NUM_DATA_ROWS\t3
NUM_DATA_COLUMNS\t7
START_TIME_FORMAT\tMM/dd/yyyy HH:mm:ss
START_TIME\t06/04/2019 13:04:23
END_HEADER
没有预定义的架构,spark只读2列:

df_static = spark.read.options(header='false', inferschema='true', multiLine=True, delimiter = "\t",mode="PERMISSIVE",).csv("/FileStore/111.txt")

root
 |-- _c0: string (nullable = true)
 |-- _c1: string (nullable = true)

定义自定义架构:

from pyspark.sql.types import *


# define it as per your data types
user_schema = StructType([
...    StructField("time", TimestampType(), True),
...    StructField("name", StringType(), True),
...    StructField("Country", StringType(), True),
...    StructField("City", StringType(), True),
...    StructField("Phone1", StringType(), True),
...    StructField("Phone2", StringType(), True),])
参考:


我有如下多个模式

user_schema1 = StructType([
...    StructField("time", TimestampType(), True),
...    StructField("name", StringType(), True),
...    StructField("Country", StringType(), True),...   
...    ])

user_schema2 = StructType([...    
...    StructField("Phone1", StringType(), True),
...    StructField("Phone2", StringType(), True),])


df_static = spark.read.schema(user_schema(send schema name dynamic)).options(header='false', multiLine=True, delimiter = "\t", mode="PERMISSIVE").csv("/FileStore/111.txt")`enter code here`

Kindly provide me the solution

我可以同时读取元数据和数据列吗?谢谢您!所以,这不可能一步到位。可以先解析元信息,然后添加文件的数据列,反之亦然。因为它本质上是多个数据行的一个元信息。
user_schema1 = StructType([
...    StructField("time", TimestampType(), True),
...    StructField("name", StringType(), True),
...    StructField("Country", StringType(), True),...   
...    ])

user_schema2 = StructType([...    
...    StructField("Phone1", StringType(), True),
...    StructField("Phone2", StringType(), True),])


df_static = spark.read.schema(user_schema(send schema name dynamic)).options(header='false', multiLine=True, delimiter = "\t", mode="PERMISSIVE").csv("/FileStore/111.txt")`enter code here`

Kindly provide me the solution