【问题标题】:How convert rdd row to a dataframe with json struct in pyspark?如何在pyspark中将rdd行转换为带有json结构的数据框?
【发布时间】:2019-03-15 22:15:25
【问题描述】:

我将以下 json 发送到路径“/home/host/test”,以便程序可以使用 spark 流捕获它并能够对其进行查询。

{"id": "1", description: "test"}
{"id": "1", description: "test"}

但是当我执行查询时,它看起来像下面的结构

root
   | --word: String (Nulleable = true)

我得到以下结果:

+ ------------------- +
| word |
---------------------
| {"id": "1", "test"}
| {"id": "1", "test"}

我需要这样的结构

root
   | --id: String (Nulleable = true)
   | --description string (Nulleable = true)

我需要得到如下结果

 ----------------
| id | description
----------------
| "1" | "test" |
| "1" | "test" |
----------------    

这是我的 pyspkark 代码

from __future__ import print_function
import os
import sys
from pyspark import SparkContext
from pyspark.sql.functions import col, explode
from pyspark.streaming import StreamingContext
from pyspark.sql import SQLContext, Row
from pyspark.sql import SQLContext


if __name__ == "__main__":

sc = SparkContext(appName="PythonSqlNetworkWordCount")
ssc = StreamingContext(sc, 3)
sqlcontextoriginal = SQLContext(sc)

# Create a socket stream on target ip:port and count the
# words in input stream of \n delimited text (eg. generated by 'nc')
lines = ssc.textFileStream("/home/host/test")

# Convert RDDs of the words DStream to DataFrame and run SQL query
def process(time, rdd):
    print("========= %s =========" % str(time))

    try:
        # Get the singleton instance of SQLContext
        sqlContext = SQLContext(rdd.context)
        # Convert RDD[String] to RDD[Row] to DataFrame
        rowRdd = rdd.map(lambda w: Row(word=w))
        wordsDataFrame = sqlContext.createDataFrame(rowRdd).toJSON()

        json = sqlContext.read.json(wordsDataFrame)
        # Register as table
        json.createOrReplaceTempView("words")
        json.printSchema()

        wordCountsDataFrame = sqlContext.sql("select * from words ")
        wordCountsDataFrame.show()

    except:
        pass

lines.foreachRDD(process)
ssc.start()
ssc.awaitTermination()

【问题讨论】:

    标签: apache-spark pyspark apache-spark-sql spark-streaming pyspark-sql


    【解决方案1】:

    好的,我找到了解决方案。

    我不得不使用 sql.read.json 直接将它作为参数传递给 rdd。

    json = sqlContext.read.json(rdd)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 2018-09-08
      • 2020-12-06
      • 2019-08-26
      • 1970-01-01
      • 2021-08-26
      相关资源
      最近更新 更多