5

dstream で json からデータフレームを作成しようとしていますが、以下のコードはデータフレームを正しく取得していないようです -

import sys
import json
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.sql import SQLContext
def getSqlContextInstance(sparkContext):
    if ('sqlContextSingletonInstance' not in globals()):
        globals()['sqlContextSingletonInstance'] = SQLContext(sparkContext)
    return globals()['sqlContextSingletonInstance']

if __name__ == "__main__":
    if len(sys.argv) != 3:
        raise IOError("Invalid usage; the correct format is:\nquadrant_count.py <hostname> <port>")

# Initialize a SparkContext with a name
spc = SparkContext(appName="jsonread")
sqlContext = SQLContext(spc)
# Create a StreamingContext with a batch interval of 2 seconds
stc = StreamingContext(spc, 2)
# Checkpointing feature
stc.checkpoint("checkpoint")
# Creating a DStream to connect to hostname:port (like localhost:9999)
lines = stc.socketTextStream(sys.argv[1], int(sys.argv[2]))
lines.pprint()
parsed = lines.map(lambda x: json.loads(x))
def process(time, rdd):
    print("========= %s =========" % str(time))
    try:
        # Get the singleton instance of SQLContext
        sqlContext = getSqlContextInstance(rdd.context)
        # Convert RDD[String] to RDD[Row] to DataFrame
        rowRdd = rdd.map(lambda w: Row(word=w))
        wordsDataFrame = sqlContext.createDataFrame(rowRdd)
        # Register as table
        wordsDataFrame.registerTempTable("mytable")
        testDataFrame = sqlContext.sql("select summary from mytable")
        print(testDataFrame.show())
        print(testDataFrame.printSchema())
    except:
        pass
parsed.foreachRDD(process)
stc.start()
# Wait for the computation to terminate
stc.awaitTermination()

エラーはありませんが、スクリプトを実行すると、ストリーミング コンテキストから json が正常に読み取られますが、値が要約またはデータフレーム スキーマに出力されません。

私が読もうとしているjsonの例 -

{"reviewerID": "A2IBPI20UZIR0U", "asin": "1384719342", "reviewerName": "cassandra tu \"うん、まあ、それはあなたのようだ...", "helpful": [0, 0], "reviewText": "ここで書くことはあまりありませんが、本来あるべきことを正確に行います。ポップ サウンドを除外します。今、私の録音ははるかに鮮明です。Amazon で最も低価格のポップ フィルターの 1 つです。 reviewTime": "2014 年 2 月 28 日"}

私はスパーク ストリーミングの初心者で、ドキュメントを読んでペット プロジェクトに取り組み始めました。ヘルプとガイダンスは大歓迎です。

4

0 に答える 0