簡體   English   中英

使用Spark和Kafka進行Twitter流式傳輸:如何在MongoDB中存儲數據

[英]Twitter streaming using spark and kafka: How store the data in MongoDB

我正在使用此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”並創建功能“保存”

tweets.foreachRDD(Save)

我將“插入”移到了此功能

def Save(rdd):
if not rdd.isEmpty():
    db.mynewcollection.insert_one(rdd)

但它不起作用

TypeError: can't pickle _thread.lock objects

誰能幫助我知道如何在MongoDB中存儲流數據

  • 發生第一個錯誤是因為您將分布式對象傳遞到db.mynewcollection.insert_one

  • 發生第二個錯誤是因為在驅動程序上初始化數據庫連接,並且通常無法對連接對象進行序列化。

盡管存在許多Spark / MongoDB連接器,但您應該看一下(使Spark,Python和MongoDB協同工作 ),通用模式是使用foreachPartition 定義助手

def insert_partition(xs):
    connection = pymongo.MongoClient('....',...)
    db = connection['twitter1']
    db.authenticate('..','...')
    db.mynewcollection.insert_many(xs)

接着:

def to_dict(s):
    return ... # Convert input to a format acceptable by `insert_many`, for example with json.loads

tweets.map(to_dict) \
    .foreachRDD(lambda rdd: rdd.foreachPartition(insert_partition))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM