Database Reference
In-Depth Information
@tweets.create_index([['id', 1]], :unique => true)
@tweets.create_index([['tags', 1], ['id', -1]])
@tag = tag
@tweets_found = 0
end
def update
puts "Starting Twitter search for '#{@tag}'..."
save_tweets_for(@tag)
print "#{@tweets_found} tweets saved.\n\n"
end
private
def save_tweets_for(term)
Twitter::Search.new(term).each do |tweet|
@tweets_found += 1
tweet_with_tag = tweet.to_hash.merge!({"tags" => [term]})
@tweets.save(tweet_with_tag)
end
end
end
All that remains is to write a script to run the TweetArchiver code against each of the
search terms. Create a file called update.rb containing the following:
require 'config'
require 'archiver'
TAGS.each do |tag|
archive = TweetArchiver.new(tag)
archive.update
end
Next, run the update script:
ruby update.rb
You'll see some status messages indicating that tweets have been found and saved. You
can verify that the script works by opening up the MongoDB shell and querying the
collection directly:
> use twitter-archive
switched to db twitter-archive
> db.tweets.count()
30
To k e e p t h e a rc h i v e c ur r e n t , y o u ca n r e r un t h e u p d a t e s c r i p t o n c e e v e r y f e w m i n u t e s
using a cron job. But that's an administrative detail. What's important here is that
you've managed to store tweets from Twitter searches in only a few lines of code. 5 Now
comes the task of displaying the results.
5
It's possible to accomplish this in far fewer lines of code. Doing so is left as an exercise to the reader.
Search WWH ::




Custom Search