LoginSignup
23
22

More than 5 years have passed since last update.

rubyでtwitterのツイートをmongodbに流し込む

Posted at

題名の通り、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"})

insertにハッシュを渡すと、それを保存します。

twitterからのデータをmongodbに保存する

以上の二つを組み合わすと、以下のようになります。

なお、日本語とそれ以外のデータとで分けて保存しています。

(ひらがなカタカナが含まれているか否かしか見てませんが)

stream.rb
# -*- 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
23
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
22