用Ruby将Twitter的推文流入MongoDB
按照标题所说的,将Twitter的推文放入mongodb中。
请预先适当安装mongodb。
另外,ruby版本为2.1.0。
安装图书馆
# mongodb用
gem install mongo bson_ext
# twitter用
gem install tweetstream
儲存來自Twitter的數據。
tweetstream有这个功能,所以只需使用它。
TweetStream.configure do |tweet_config|
tweet_config.consumer_key = consumer_key
tweet_config.consumer_secret = consumer_secret
tweet_config.oauth_token = oauth_token
tweet_config.oauth_token_secret = oauth_token_secret
tweet_config.auth_method = :oauth
end
TweetStream::Client.new.sample do |status|
p status.text
end
此外,由于可以使用stasut.to_h进行哈希化,因此将该状态直接保存在MongoDB中。
将数据保存到MongoDB中。
mongodbには以下のように書くことで接続できます。
connection = Mongo::Connection.new
db = connection.db('twitter_database') #db名
col = db.collection('twittr_table') #テーブル名
col.insert({test: "test"})
当将哈希表传递给插入函数时,它会保存该哈希表。
将来自Twitter的数据保存到MongoDB中
将上述两者结合起来,将会变成以下的形式。
顺便提一下,我们将日语数据和其他数据分开保存。(只看平假名片假名是否包含)
# -*- coding: utf-8 -*-
require 'yaml'
require 'tweetstream'
require 'mongo'
class TwitterWorker
def initialize(config)
TweetStream.configure do |tweet_config|
tweet_config.consumer_key = config["consumer_key"]
tweet_config.consumer_secret = config["consumer_secret"]
tweet_config.oauth_token = config["oauth_token"]
tweet_config.oauth_token_secret = config["oauth_token_secret"]
tweet_config.auth_method = :oauth
end
@client = TweetStream::Client.new
connection = Mongo::Connection.new
db = connection.db('twitter_jp')
@jp_col = db.collection('twitter_jp')
db = connection.db('twitter_nojp')
@nojp_col = db.collection('twitter_nojp')
end
def start
@client.sample do |status|
if /[ぁ-んァ-ヴ]+/u =~ status.text then
@jp_col.insert(status.to_h)
else
@nojp_col.insert(status.to_h)
end
end
end
end
worker = TwitterWorker.new(config = YAML.load_file("twitter.yml"))
worker.start