Search code examples
javatwitter4j

Twitter4j : difference between search and track


I begin with Twitter4j, I need to get Tweet from Stream with a specific hashtag.

I found 2 methods :

StatusListener listener = new StatusListener() {
...
    public void onStatus(Status status) {
                statuses.add(status);
                HashtagEntity[] H = status.getHashtagEntities();
                System.out.println(statuses.size()+":Got tweet:\n" + status.getText()+"\n"+status.getUser().getScreenName()
                        + " | "+status.getId()+" | "+H.length+"\n");
                if(H.length>0){
                    for(int i=0;i<H.length-1;i++){
                        System.out.print(H[i]+"");
                    }
                }
                if (statuses.size() > nbremax) {
                    synchronized (lock) {
                        lock.notify();
                    }
                    System.out.println("unlocked");
                }
            }
}
FilterQuery fq = new FilterQuery();    
fq.track("#hashtag");
TwitterStream twitterStream = ...;
twitterStream.addListener(listener);
twitterStream.filter(fq);

and

Twitter twitter = ...;
Query query = new Query("#hastag");
QueryResult result = twitter.search(query);
for (Status status : result.getTweets()) {
    HashtagEntity[] H = status.getHashtagEntities();
    System.out.println("Got tweet:\n" + status.getText()
            +"\n"+status.getUser().getScreenName()+ " | "+status.getId()+
            " | retweet ? "+status.isRetweet()+" | "+H.length);
    System.out.println(status.getCreatedAt()+" | "+status.getGeoLocation()+
                    " | "+status.getPlace()+" | "+status.getSource());
    if(H.length>0){
        for(int i=0;i<H.length;i++){
            System.out.print(H[i].getText()+" ; ");
            if(i==H.length-1){
               System.out.println("\n");
            }
        }
    }

What's the difference between them ? Which method is the best for search a specific hashtag?


Solution

  • search : you will retrieve all existing tweets containing the given hashtag right now.

    track : all tweets containing the given hashtag will be streamed to you from now.