如何将流数据从spark汇到Mongodb?

时间:2018-06-04 12:21:12

标签: mongodb apache-spark pyspark

我正在使用pyspark从Kafka读取流数据,然后我想将该数据汇入mongodb。我已经包含了所有必需的软件包,但它会引发错误 UnsupportedOperationException:数据源com.mongodb.spark.sql.DefaultSource不支持流式写入

以下链接与我的问题无关

Writing to mongoDB from Spark

Spark to MongoDB via Mesos

这是完整的错误堆栈跟踪

  

回溯(最近一次调用最后一次):文件" /home/b3ds/kafka-spark.py",   第85行,在       。选项(" com.mongodb.spark.sql.DefaultSource"" mongodb的://本地主机:27017 / twitter.test&#34)\   文件   " /home/b3ds/hdp/spark/python/lib/pyspark.zip/pyspark/sql/streaming.py" ;,   第827行,在启动文件中   " /home/b3ds/hdp/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py" ;,   第1133行,在调用文件中   " /home/b3ds/hdp/spark/python/lib/pyspark.zip/pyspark/sql/utils.py" ;,   第63行,在deco文件中   " /home/b3ds/hdp/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py" ;,   第319行,在get_return_value py4j.protocol.Py4JJavaError:错误   在调用o122.start时发生了。 :   java.lang.UnsupportedOperationException:数据源   com.mongodb.spark.sql.DefaultSource不支持流式写入           在org.apache.spark.sql.execution.datasources.DataSource.createSink(DataSource.scala:287)           在org.apache.spark.sql.streaming.DataStreamWriter.start(DataStreamWriter.scala:272)           at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)           at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)           at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)           at java.lang.reflect.Method.invoke(Method.java:498)           at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)           在py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)           在py4j.Gateway.invoke(Gateway.java:280)           at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)           在py4j.commands.CallCommand.execute(CallCommand.java:79)           在py4j.GatewayConnection.run(GatewayConnection.java:214)           在java.lang.Thread.run(Thread.java:748)

这是我的pyspark代码

from __future__ import print_function
import sys
from pyspark.sql.functions import udf
from pyspark.sql import SparkSession
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
from pyspark.sql.types import StructType
from pyspark.sql.types import *
import json
from pyspark.sql.functions import struct
from pyspark.sql.functions import *
import datetime

json_schema = StructType([
  StructField("twitterid", StringType(), True),
  StructField("created_at", StringType(), True),
  StructField("tweet", StringType(), True),
  StructField("screen_name", StringType(), True)
])

def parse_json(df):
    twitterid   = json.loads(df[0])['id']
    created_at  = json.loads(df[0])['created_at']
    tweet       = json.loads(df[0])['text']
    tweet       = json.loads(df[0])['text']
    screen_name = json.loads(df[0])['user']['screen_name']
    return [twitterid, created_at, tweet, screen_name]

def convert_twitter_date(timestamp_str):
    output_ts = datetime.datetime.strptime(timestamp_str.replace('+0000 ',''), '%a %b %d %H:%M:%S %Y')
    return output_ts

if __name__ == "__main__":

        spark = SparkSession\
                        .builder\
                        .appName("StructuredNetworkWordCount")\
                        .config("spark.mongodb.input.uri","mongodb://192.168.1.16:27017/twitter.test")\
                        .config("spark.mongodb.output.uri","mongodb://192.168.1.16:27017/twitter.test")\
                        .getOrCreate()
        events = spark\
                        .readStream\
                        .format("kafka")\
                        .option("kafka.bootstrap.servers", "localhost:9092")\
                        .option("subscribe", "twitter")\
                        .load()
        events = events.selectExpr("CAST(value as String)")

        udf_parse_json = udf(parse_json , json_schema)
        udf_convert_twitter_date = udf(convert_twitter_date, TimestampType())
        jsonoutput = events.withColumn("parsed_field", udf_parse_json(struct([events[x] for x in events.columns]))) \
                                        .where(col("parsed_field").isNotNull()) \
                                        .withColumn("created_at", col("parsed_field.created_at")) \
                                        .withColumn("screen_name", col("parsed_field.screen_name")) \
                                        .withColumn("tweet", col("parsed_field.tweet")) \
                                        .withColumn("created_at_ts", udf_convert_twitter_date(col("parsed_field.created_at")))

        windowedCounts = jsonoutput.groupBy(window(jsonoutput.created_at_ts, "1 minutes", "15 seconds"),jsonoutput.screen_name)$

        mongooutput = jsonoutput \
                        .writeStream \
                        .format("com.mongodb.spark.sql.DefaultSource")\
                        .option("com.mongodb.spark.sql.DefaultSource","mongodb://localhost:27017/twitter.test")\
                        .start()
        mongooutput.awaitTermination()

我看过mongodb文档说它支持mongo sink的火花

https://docs.mongodb.com/spark-connector/master/scala/streaming/

1 个答案:

答案 0 :(得分:0)

  

我已经看过mongodb文档说它支持mongo sink的火花

有哪些文档声明,您可以使用标准RDD API使用旧版Streaming(DStream)API编写每个RDD。

它并不表示MongoDB支持结构化流,而它不支持。由于你使用PySpark,forEach writer无法访问,你必须等待,直到(如果有的话)更新MongoDB包以支持流操作。