【发布时间】:2020-06-20 05:26:51
【问题描述】:
我真的很想在使用 PySpark-SQL 解析嵌套的 JSON 数据方面得到一些帮助。数据具有以下架构(空格是出于保密目的而进行的编辑...)
架构
root
|-- location_info: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- restaurant_type: string (nullable = true)
| | |
| | |
| | |-- other_data: array (nullable = true)
| | | |-- element: struct (containsNull = true)
| | | | |-- other_data_1 string (nullable = true)
| | | | |-- other_data_2: string (nullable = true)
| | | | |-- other_data_3: string (nullable = true)
| | | | |-- other_data_4: string (nullable = true)
| | | | |-- other_data_5: string (nullable = true)
| | |
| | |-- latitude: string (nullable = true)
| | |
| | |
| | |
| | |
| | |
| | |-- longitude: string (nullable = true)
| | |
| | |
| | |
| | |-- timezone: string (nullable = true)
|-- restaurant_id: string (nullable = true)
我的目标 我基本上想将数据放入以下数据框
restaurant_id | latitude | longtitude | timezone
我试过了
dfj = spark.read.option("multiLine", False).json("/file/path")
result = dfj.select(col('restaurant_id'),
explode(col('location_info')).alias('location_info') )
# SQL operation
result.createOrReplaceTempView('result')
subset_data = spark.sql(
'''
SELECT restaurant_id, location_info.latitude,location_info.longitude,location_info.timestamp
FROM result
'''
).show()
# Also tried this to read in
source_df_1 = spark.read.json(sc.wholeTextFiles("/file/path")
.values()
.flatMap(lambda x: x
.replace("{", "#!#")
.split("#!#")))
但奇怪的是,它只为第一个对象或餐厅 ID 提供了以下内容
+-------+-----------+------------+--------------------+
|restaurant_id|latitude|longitude|timestamp|
+-------+-----------+------------+--------------------+
| 25|2.0|-8.0|2020-03-06T03:00:...|
| 25|2.0|-8.0|2020-03-06T03:00:...|
| 25|2.0|-8.0|2020-03-06T03:00:...|
| 25|2.0|-8.0|2020-03-06T03:01:...|
| 25|2.0|-8.0|2020-03-06T03:01:...|
+-------+-----------+------------+--------------------+
我的研究表明,这可能与 JSON 文件的源结构方式有关。例如:
{}{
}{
}
因此不是多线或其他东西。想知道该怎么做?
非常感谢您的阅读,任何帮助将不胜感激。我知道我总是可以指望 SO 提供帮助
【问题讨论】:
-
如果您可以为多个餐厅共享 json(擦洗任何重要的内容),那将非常有帮助。我认为您的意思是 timestamp=timezone .,对吗?
标签: apache-spark pyspark apache-spark-sql databricks