LoginSignup
8

More than 5 years have passed since last update.

rubyでtwitter/json-streamを使用し、Streaming APIからmongoDBに保存

Last updated at Posted at 2014-02-16

TwitterのStreaming APIを使用するにあたって、取得したツイートすべてをmongoDBに保存するにはtwitter/json-streamを使うのが簡単そうだったので…

main.rb
# encoding: utf-8
#! ruby -Ku

require "rubygems"
require "bundler"
require "twitter/json_stream"
require "json"
require "mongo"
Bundler.require

#.envファイルより環境変数load
Dotenv.load

#mongodb接続用定義
db = Mongo::Connection.from_uri(ENV["MONGODB_URL"]).db(ENV["MONGODB_DB"])
#コレクション定義
@items = db.collection(ENV["MONGODB_COLLECTION"])

#EventMachine
EM.run do
  #Twitter Streaming APIのsampleStremの定義
  samplestream = Twitter::JSONStream.connect(
    :host => "stream.twitter.com",          #接続ホスト
    :path => "/1.1/statuses/sample.json",   #接続ホスト以降のURL
    :ssl => true,                           #SSL通信
    :oauth => {                             #oauth認証情報
      :consumer_key => ENV["CONSUMER_KEY"],
      :consumer_secret => ENV["CONSUMER_SECRET"],
      :access_key => ENV["ACCESS_KEY"],
      :access_secret => ENV["ACCESS_SECRET"]
    }
  )

  #sampleStreamより取得したアイテムをmongodbへ挿入
  samplestream.each_item do |item|
    tweet = JSON.parse(item)  #ツイートの内容をjson形式に変換
    if tweet["lang"] == "ja"  #日本語ツイートのみ取得対象とする
      @items.insert(tweet)    #json形式に変換したツイートをmongodbへ挿入
    end
  end
end

Gemfileに使用するgemを記載

Gemfile
ruby "2.1.0"

source "https://rubygems.org"

gem "twitter-stream"
gem "json"
gem "mongo"
gem "bson"
gem "bson_ext"
gem "dotenv"

.envファイルにはmongoDB接続及びTwitterの認証キーをセットする

#mongoDB
MONGODB_URL = "mongodb://<uid>:<password>@localhost/db_name"
MONGODB_DB = "db_name"
MONGODB_COLLECTION = "collection_name"

#Twitter
CONSUMER_KEY = "xxxxxxxx"
CONSUMER_SECRET = "xxxxxxxx"
ACCESS_KEY = "xxxxxxxx"
ACCESS_SECRET = "xxxxxxxx"

実行する時は以下のコマンド
bundle install
bundle exec ruby main.rb

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
8