【问题标题】:PySpark parse Json using RDD and json.loadPySpark 使用 RDD 和 json.load 解析 Json
【发布时间】:2018-02-08 04:34:51
【问题描述】:
{

  "city": "Tempe",
  "state": "AZ",
  ...
  "attributes": [
    "BikeParking: True",
    "BusinessAcceptsBitcoin: False",
    "BusinessAcceptsCreditCards: True",
    "BusinessParking: {'garage': False, 'street': False, 'validated': False, 'lot': True, 'valet': False}",
    "DogsAllowed: False",
    "RestaurantsPriceRange2: 2",
    "WheelchairAccessible: True"
  ],
  ...
}

您好,我正在使用 PySpark,我正在尝试输出 (state, BusinessAcceptsBitcoin) 的元组,目前我正在做:

csr = (dataset
        .filter(lambda e:"city" in e and "BusinessAcceptsBitcoin" in e)
        .map(lambda e: (e["city"],e["BusinessAcceptsBitcoin"]))
        .collect()
        )

但是这个命令失败了。如何获取“BusinessAcceptsBitcoin”和“city”字段?

【问题讨论】:

标签: python json apache-spark pyspark


【解决方案1】:

您可以使用 Dataframe 和 UDF 来解析“属性”字符串。

根据您提供的示例数据,“属性”似乎不是正确的 JSON 或字典。

假设 'attributes' 只是一个字符串,这里是一个使用数据框和 Udf 的示例代码。

from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *

spark = SparkSession \
            .builder \
            .appName("test") \
            .getOrCreate()

#sample data
data=[{

  "city": "Tempe",
  "state": "AZ",
  "attributes": [
    "BikeParking: True",
    "BusinessAcceptsBitcoin: False",
    "BusinessAcceptsCreditCards: True",
    "BusinessParking: {'garage': False, 'street': False, 'validated': False, 'lot': True, 'valet': False}",
    "DogsAllowed: False",
    "RestaurantsPriceRange2: 2",
    "WheelchairAccessible: True"
  ]
}]
df=spark.sparkContext.parallelize(data).toDF()

用于解析字符串的用户定义函数

def get_attribute(data,attribute):
    return [list_item for list_item in data if attribute in list_item][0]

注册 udf

udf_get_attribute=udf(get_attribute, StringType

数据框

df.withColumn("BusinessAcceptsBitcoin",udf_get_attribute("attributes",lit("BusinessAcceptsBitcoin"))).select("city","BusinessAcceptsBitcoin").show(truncate=False)

样本输出

+-----+-----------------------------+
|city |BusinessAcceptsBitcoin       |
+-----+-----------------------------+
|Tempe|BusinessAcceptsBitcoin: False|
+-----+-----------------------------+

您也可以使用相同的 udf 查询任何其他字段,例如

df.withColumn("DogsAllowed",udf_get_attribute("attributes",lit("DogsAllowed"))).select("city","DogsAllowed").show(truncate=False)

【讨论】:

  • 抱歉,我不能为此使用数据框!!只能是 RDD!
猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2020-04-06
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
相关资源
最近更新 更多