背景:ストリーミング API から JSON オブジェクトを取得し、それらを pymongo を使用して MongoDB に格納する (一度に 25 個の一括挿入)
ようにpython
モジュールをセットアップしました。curl
比較のために、同じストリーミング API からへの bash コマンドも用意していpipe
ますmongoimport
。これらのアプローチはどちらも、データを別々のコレクションに保存します。
定期的にcount()
、コレクションを監視して、それらがどのように機能するかを確認します。
これまでのところ、python
モジュールはアプローチよりも約 1000 個の JSON オブジェクトに遅れをとっていますcurl | mongoimport
。
問題:python
モジュールを ~ と同期するよう
に最適化するにはどうすればよい curl | mongoimport
ですか?
tweetstream
Twitter APIではなくサードパーティのストリーミングサービスを利用しているため利用できません。
誰かがここで私を助けてくれませんか?
Python
モジュール:
class StreamReader:
def __init__(self):
try:
self.buff = ""
self.tweet = ""
self.chunk_count = 0
self.tweet_list = []
self.string_buffer = cStringIO.StringIO()
self.mongo = pymongo.Connection(DB_HOST)
self.db = self.mongo[DB_NAME]
self.raw_tweets = self.db["raw_tweets_gnip"]
self.conn = pycurl.Curl()
self.conn.setopt(pycurl.ENCODING, 'gzip')
self.conn.setopt(pycurl.URL, STREAM_URL)
self.conn.setopt(pycurl.USERPWD, AUTH)
self.conn.setopt(pycurl.WRITEFUNCTION, self.handle_data)
self.conn.perform()
except Exception as ex:
print "error ocurred : %s" % str(ex)
def handle_data(self, data):
try:
self.string_buffer = cStringIO.StringIO(data)
for line in self.string_buffer:
try:
self.tweet = json.loads(line)
except Exception as json_ex:
print "JSON Exception occurred: %s" % str(json_ex)
continue
if self.tweet:
try:
self.tweet_list.append(self.tweet)
self.chunk_count += 1
if self.chunk_count % 1000 == 0
self.raw_tweets.insert(self.tweet_list)
self.chunk_count = 0
self.tweet_list = []
except Exception as insert_ex:
print "Error inserting tweet: %s" % str(insert_ex)
continue
except Exception as ex:
print "Exception occurred: %s" % str(ex)
print repr(self.buff)
def __del__(self):
self.string_buffer.close()
読んでくれてありがとう。