Searching Twitter

Many web applications integrate Twitter into their pages to display realtime news and thoughts. Here’s a code snippet showing how to search Twitter using the twitter4j library.

Twitter’s search API doesn’t return all search results at once; instead it returns “pages” of results, with each page containing 100 tweets matching the search criteria. The following code snippet runs through many pages of search results using a while loop, so it may take some time to process. Run it within a backend if you’re searching for a particularly popular phrase or doing heavy processing on each tweet.

The variable twitter represents a twitter4j.Twitter object, and status represents a single tweet. You can extract tweet information from that object; for example status.getText() would return the text of the tweet. Edit the string “google app engine” to whatever text you’re searching Twitter for.

twitter4j.Query twitter_query = new twitter4j.Query("google app engine");
twitter_query.setCount(100);
//This while loop runs through each page of the returned 
//tweets. One page of results (100 tweets) is processed 
//per loop.
while (twitter_query != null) {
    //A list of the returned tweets, representing 1 page (100 tweets).
    QueryResult twitter_results = twitter.search(twitter_query);
    //Run through this page of results and access each returned tweet.
    for (Status status : twitter_results.getTweets()) {
        //Do something with the status object.
    }
    //Retrieves a Query representing the next page of results.
    twitter_query = twitter_results.nextQuery();
}//end while loop running through pages of returned results.