pyspark 在azure synapse笔记本中使用spark.sql提取json列

5vf7fwbs  于 2023-01-25  发布在  Spark
关注(0)|答案(1)|浏览(161)

我有一个 parquet 文件作为源,我加载了该 parquet 文件使用PySpark笔记本,如下所示:

df_Employee = spark.read.parquet(<filename>)
df_Employee .createOrReplaceTempView("employee_data")

这张table是这样的

Employee Table:

-Name
-Salary
-Company
-Address (datatype=string)
 --street.name
 --street.number
 --postalcode
-JoiningDate

我有下面的代码,但我在如何street.name从上面的SQL表中提取www.example.com & street.number上遇到了麻烦,下面是我的代码

df=spark.sql(f'''
select Name, Salary, Company, json_extract(Address,'$."street.name"') as StreetName
from employee_data
''')

但是json_extract(Address,'$.”street.name“')作为街道名称抛出错误。如何提取此嵌套json字段?

lvmkulzt

lvmkulzt1#

我根据员工表在我的环境中创建了相同的样本数据框:

dat1= [("vamsi", 20000, "MID", '{"street.name": "App socity", "street.number": "912", "postalcode": "523112"}', "2023-01-20"),
        ("rakesh",30000, "MID", '{"street.name": "Mind space", "street.number": "456", "postalcode": "600062"}', "2023-01-19")]
col = ["Name", "Salary", "Company", "Address", "JoiningDate"]

df1 = spark.createDataFrame(dat1, col)
df1.createOrReplaceTempView("sample_table")

  • 您可以使用以下代码实现相同的要求 *。
df1 = spark.sql(f'''select Name, Salary, Company, json_tuple(Address, 'street.name', 'street.number') as (StreetName, StreetNumber)
from sample_table''')
df1.show()

相关问题