我是 Spark 的初学者。我正在关注 PySpark 上的视频类(class)。 我正在尝试使用以下代码将 json 字符串转换为数据框。
import pyspark as ps
from pyspark.sql import HiveContext # to interface dataframe API
sc = ps.SparkContext()
hive_context = HiveContext(sc)
# some code .... and build meals_json
meals_json.take(1) # below is output of this code
#['{"meal_id": 1, "dt": "2013-01-01", "type": "french", "price": 10}']
# some more code
meals_dataframe = hive_context.jsonRDD(meals_json)
meals_dataframe.first()
在尝试运行最后一行时,出现以下错误。
AttributeError Traceback (most recent call last)
<ipython-input-19-43e4f3006ac3> in <module>()
----> 1 meals_dataframe = hive_context.jsonRDD(meals_json)
2 meals_dataframe.first()
AttributeError: 'HiveContext' object has no attribute 'jsonRDD'
我在网上搜索过,但找不到讨论此问题的任何资源。我在带有 Python 3.5 的 jupyter notebook 上使用 Spark 2.1.1 运行这段代码。
从文档中,我可以看到 jsonRDD 是从 class org.apache.spark.sql.SQLContext 继承的。我不太确定,可能是什么原因。 任何建议都会有所帮助。谢谢。
请您参考如下方法:
sqlContext.jsonRDD 是 deprecated .从 1.4.0 开始,它已被替换为 read().json()。我在下面包含了一个适用于 Spark 2.1.1 的示例
import json
from pyspark.sql.types import StructField, StructType, IntegerType, StringType
r = [{'a': 'aaa', 'b': 'bbb', 'c': 'ccc'},
{'a': 'aaaa','b': 'bbbb','c': 'cccc','d': 'dddd'}]
r = [json.dumps(d) for d in r]
# known schema
schema = ['a', 'b', 'c', 'd']
fields = [StructField(field_name, StringType(), True) for field_name in schema]
schema = StructType(fields)
rdd = sc.parallelize(r)
df = sqlContext.read.schema(schema).json(rdd)
df.collect()
这会在 Spark 2.1.1 上产生以下输出:
[Row(a=u'aaa', b=u'bbb', c=u'ccc', d=None),
Row(a=u'aaaa', b=u'bbbb', c=u'cccc', d=u'dddd')]
请注意,此代码段的第一部分很大程度上受到了 this question 的启发。在 Apache Spark 用户列表中
