【问题标题】:Querying json object in dataframe using Pyspark使用 Pyspark 查询数据框中的 json 对象
【发布时间】:2017-01-10 02:11:10
【问题描述】:

我有一个具有以下架构的 MySql 表:

id-int
path-varchar
info-json {"name":"pat", "address":"NY, USA"....}

我使用 JDBC 驱动程序将 pyspark 连接到 MySql。我可以使用从 mysql 检索数据

df = sqlContext.sql("select * from dbTable")

这个查询一切正常。我的问题是,如何查询“信息”列?例如,下面的查询在 MySQL shell 中工作正常并检索数据,但 Pyspark (2+) 不支持。

select id, info->"$.name" from dbTable where info->"$.name"='pat'

【问题讨论】:

    标签: python mysql json apache-spark pyspark


    【解决方案1】:
    from pyspark.sql.functions import *
    res = df.select(get_json_object(df['info'],"$.name").alias('name'))
    res = df.filter(get_json_object(df['info'], "$.name") == 'pat')
    

    已经有一个名为get_json_object

    的函数

    根据你的情况:

    df = spark.read.jdbc(url='jdbc:mysql://localhost:3306', table='test.test_json',
                         properties={'user': 'hive', 'password': '123456'})
    df.createOrReplaceTempView('test_json')
    res = spark.sql("""
    select col_json,get_json_object(col_json,'$.name') from test_json
    """)
    res.show()
    

    Spark sql 和 HIVE sql 差不多,你可以看到

    https://cwiki.apache.org/confluence/display/Hive/Home

    【讨论】:

    • 感谢您的回复。此方法仅在数据加载到数据框中时有效。有数十万条记录。加载完整表并针对它过滤数据可能不是有效的方法。有没有办法检索仅与查询匹配的数据(json 搜索)而不是加载完整的表?
    猜你喜欢
    • 2022-01-02
    • 2021-11-18
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多