Search code examples
javatwittertwitter4j

How to search tweets from a particular userTimeline by a keyword in twitter4j


If I want to get recent tweets from a particular user I can do that only using the username in twitter4j

twitter.getUserTimeline(username)

I can also look globally for all tweets that match a search criteria:

twitter.search(new Query(keyword))

Is there a way I can search within all of the tweets from one user's timeline for a particular keyword?


Solution

  • Yes, it's possible using the Twitter Search API but the caveat is that it will only return tweets going back 7 days.

    The Twitter Search API is part of Twitter’s REST API. It allows queries against the indices of recent or popular Tweets and behaves similarly to, but not exactly like the Search feature available in Twitter mobile or web clients, such as Twitter.com search. The Twitter Search API searches against a sampling of recent Tweets published in the past 7 days.

    Before getting involved, it’s important to know that the Search API is focused on relevance and not completeness. This means that some Tweets and users may be missing from search results. If you want to match for completeness you should consider using a Streaming API instead.

    To use the Twitter4J API search(query) the query would be from:<username> <keyword>.

    The Streaming API can be used for search but would not really apply as it's designed to return large amounts of tweets from many users at that moment.

    The thorough approach would be to go through every tweet on a user's timeline and do the search yourself. This would be much more involved but not that hard actually. You would use the GET statuses/user_timeline API (getUserTimeline() in Twitter4J) and then search your keyword in the text field.