gpt4 book ai didi

json - 在模式 rdd 中分解 json 数组

转载 作者:行者123 更新时间:2023-12-03 18:32:30 29 4
gpt4 key购买 nike

我有一个像:

{"name":"Yin", "address":[{"city":"Columbus","state":"Ohio"},{"city":"Columbus","state":"Ohio"}]} 
{"name":"Michael", "address":[{"city":null, "state":"California"},{"city":null, "state":"California"}]}

这里的地址是一个数组,如果我使用 sqlContext.jsonfile我在模式 rdd 中获取数据如下:
[Yin , [(Columbus , Ohio) , (Columbus , Ohio)] 
[Micheal , [(null, California) , (null, California)]

我想分解现有的数组,并希望架构 rdd 中的数据采用以下格式:
[Yin, Columbus, Ohio] 
[Yin, Columbus, Ohio]
[Micheal, null, California]
[Micheal, null, California]

我正在使用 Spark SQL

最佳答案

典型的建议是为此退出 sql,但如果您想继续使用 SQL,这里是我从邮件列表中询问这个问题得到的答案(nabble 由于某种原因没有显示响应):

来自迈克尔·阿姆布鲁斯特

您可以使用横向 View 爆炸(使用 HiveContext ),但似乎缺少的是 jsonRDD 将 json 对象转换为结构(具有固定顺序的固定键),并且使用 . 访问结构中的字段

val myJson = sqlContext.jsonRDD(sc.parallelize("""{"foo":[{"bar":1},{"baz":2}]}""" :: Nil))
myJson.registerTempTable("JsonTest")​
val result = sql("SELECT f.bar FROM JsonTest LATERAL VIEW explode(foo) a AS f").collect()

myJson: org.apache.spark.sql.DataFrame = [foo: array<struct<bar:bigint,baz:bigint>>]
result: Array[org.apache.spark.sql.Row] = Array([1], [null])

在 Spark 1.3 中,您还可以通过手动指定 JSON 的模式,向 jsonRDD 提示您希望将 json 对象转换为 Maps(非统一键)而不是结构体。
import org.apache.spark.sql.types._
val schema =
StructType(
StructField("foo", ArrayType(MapType(StringType, IntegerType))) :: Nil)

sqlContext.jsonRDD(sc.parallelize("""{"foo":[{"bar":1},{"baz":2}]}""" :: Nil), schema).registerTempTable("jsonTest")

val withSql = sql("SELECT a FROM jsonTest LATERAL VIEW explode(foo) a AS a WHERE a['bar'] IS NOT NULL").collect()

val withSpark = sql("SELECT a FROM jsonTest LATERAL VIEW explode(foo) a AS a").rdd.filter {
case Row(a: Map[String, Int]) if a.contains("bar") => true
case _: Row => false
}.collect()
schema: org.apache.spark.sql.types.StructType = StructType(StructField(foo,ArrayType(MapType(StringType,IntegerType,true),true),true))
withSql: Array[org.apache.spark.sql.Row] = Array([Map(bar -> 1)])
withSpark: Array[org.apache.spark.sql.Row] = Array([Map(bar -> 1)])

关于json - 在模式 rdd 中分解 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29902234/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com