【发布时间】:2018-09-18 03:28:03
【问题描述】:
我正在使用这个 python 代码收集 Twitter 流数据 https://github.com/sridharswamy/Twitter-Sentiment-Analysis-Using-Spark-Streaming-And-Kafka/blob/master/app.py
之后,我运行此代码来创建流式上下文并将数据存储在 MongoDB 中。
def main():
conf = SparkConf().setMaster("local[2]").setAppName("Streamer")
sc = SparkContext(conf=conf)
ssc = StreamingContext(sc, 10)
ssc.checkpoint("checkpoint")
kstream = KafkaUtils.createDirectStream(
ssc, topics = ['topic1'], kafkaParams = {"metadata.broker.list":
'localhost:9092'})
tweets = kstream.map(lambda x: x[1].encode("ascii", "ignore"))
#................insert in MonGODB.........................
db.mynewcollection.insert_one(tweets)
ssc.start()
ssc.awaitTerminationOrTimeout(100)
ssc.stop(stopGraceFully = True)
if __name__=="__main__":
urllib3.contrib.pyopenssl.inject_into_urllib3()
connection = pymongo.MongoClient('....',...)
db = connection['twitter1']
db.authenticate('..','...')
main()
但我收到了这个错误:
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
我也尝试使用'foreachRDD'并创建函数'save'
tweets.foreachRDD(Save)
我将“插入”移到了这个函数中
def Save(rdd):
if not rdd.isEmpty():
db.mynewcollection.insert_one(rdd)
但它不起作用
TypeError: can't pickle _thread.lock objects
谁能帮我知道如何在 MongoDB 中存储流数据
【问题讨论】:
标签: python mongodb apache-spark apache-kafka spark-streaming