Articles · 2014

Realtime Twitter Sentiment Analysis with Storm and Elasticsearch

Twitter analysis becomes one of the most popular fields of research because of its solid usage by millions people across the globe. There are many interesting scientific and research problems were solved using the analysis how and that people tweet. In this article we want to show how easy could be build a simple processing flow that can show interesting statistics out of twitter data.

Archived article, first published in 2014. Kept as it was written; some tools and versions have moved on since.

Problem

We want to build a flow which could be easy to use for monitoring tweets sentiment in realtime. So, to start we need to select stack of technologies that can help to do that. One of the most popular frameworks for processing realtime streams is Apache Storm. Current stable version is 0.9.1-incubating. For string data we choose Elasticsearch.

Twitter Stream

Twitter Inc. allow to obtain some amount of tweets as a stream.They allow to filter such stream by language, keywords or location. For our research it's important to have English-only tweets, since we are limited by the linguistic analyses tool.

TwitterStreamSpout.java
TwitterStream twitterStream = new TwitterStreamFactory(
    new ConfigurationBuilder().setJSONStoreEnabled(true).build())
    .getInstance();

twitterStream.addListener(listener);
twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
AccessToken token = new AccessToken(accessToken, accessTokenSecret);
twitterStream.setOAuthAccessToken(token);

if (keywords == null) {
    twitterStream.sample();
}
else {
    FilterQuery query = new FilterQuery();

    query.track(keywords);
    if (language != null && language.length > 0) {
        query.language(language);
    }

    twitterStream.filter(query);
}
TwitterHappinessTopology.java
TopologyBuilder builder = new TopologyBuilder();

builder.setSpout(
    "spout",
    new TwitterStreamSpout(
        twitterConsumerKey,
        twitterConsumerSecret,
        twitterAccessTokenKey,
        twitterAccessTokenSecret,
        twitterQueryKeywords,
        twitterQueryLanguage)
);

builder.setBolt(
    "sentiment",
    new SentimenterBolt()
).shuffleGrouping("spout");

builder.setBolt(
    "counter",
    new CounterBolt(60)
).shuffleGrouping("sentiment");

builder.setBolt(
    "es_counts",
    new ESWriterBolt(
         esClusterName,
         esHost,
         esPort,
         esIndexNameForCounts,
         esLocalMode)
).shuffleGrouping("counter", "counts");

builder.setBolt(
    "mood",
    new MoodEstimatorBolt()
).shuffleGrouping("counter", "mood");

builder.setBolt(
    "es_mood",
    new ESWriterBolt(
         esClusterName,
         esHost,
         esPort,
         esIndexNameForMood,
         esLocalMode)
).shuffleGrouping("mood");

Sentiment

For sentiment analysis we use Stanford CoreNLP. Stanford CoreNLP provides a set of natural language analysis tools written in Java. It supports 5 level of sentiment: from 0 (very Negative) to 4 (Very Positive).

SentimenterBolt.java
/**
 * Return a sentiment value of the input string.
 *
 * If input string empty or null, this method returns null, otherwise
 * 0 - Very Negative
 * 1 - Negative
 * 2 - Neutral
 * 3 - Positive
 * 4 - Very Positive
 *
 * @param  tweet  string content of the Twitter status
 * @return        sentiment value [0, 4]
 */
private Integer getSentiment(String tweet) {
    if (tweet == null || tweet.length() < 1) {
        log.warn("Empty tweet detected, skipping ...");
        return null;
    }

    // avoid badly encoded emoticons
    tweet = tweet.replaceAll("[^\\x00-\\x7f-\\x80-\\xad]", "");

    Integer sentiment = 0;
    int longestChunk = 0;

    Annotation annotation = pipelineNLP.process(tweet);
    for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) {
        Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class);
        Integer sentimentClass = RNNCoreAnnotations.getPredictedClass(tree);
        String chunk = sentence.toString();
        if (chunk.length() > longestChunk) {
            sentiment = sentimentClass;
            longestChunk = chunk.length();
        }
    }
    return sentiment;
}
CounterBolt.java
private boolean isTickTuple(Tuple tuple) {
    return tuple.getSourceComponent().equals(Constants.SYSTEM_COMPONENT_ID)
        && tuple.getSourceStreamId().equals(Constants.SYSTEM_TICK_STREAM_ID);
}

private boolean isLongTermTickTuple() {
    int ticksFor30Minutes = Math.round(1800 / tickFrequencyInSeconds);
    return tickTupleCount > 0 && tickTupleCount % ticksFor30Minutes == 0;
}
CounterBolt.java
@Override
public void execute(Tuple tuple) {
    if (isTickTuple(tuple)) {
        Date now = new Date();
        if (isLongTermTickTuple()) {
            Map<String, Integer> longTermCounts = sentimentPeriodCounter.getAllForPeriod("longTerm");
            sentimentPeriodCounter.reset("longTerm");
            collector.emit("counts", new Values(longTermCounts, "long", now));
            collector.emit("mood", new Values(longTermCounts, "long", now));
            log.info("Emiting longTerm counts ...");
        }

        Map<String, Integer> shortTermCounts = sentimentPeriodCounter.getAllForPeriod("shortTerm");
        sentimentPeriodCounter.reset("shortTerm");
        collector.emit("counts", new Values(shortTermCounts, "short", now));
        collector.emit("mood", new Values(shortTermCounts, "short", now));
        log.info("Emiting shortTerm counts ...");

        tickTupleCount++;
        collector.ack(tuple);
        return;
    }

    final Integer sentiment = (Integer) tuple.getValueByField("sentiment");
    if (sentiment == null || sentiment < 0 || sentiment > sentimentToClass.length) {
        // undefined sentiment, so just ACK the tuple without any action
        log.warn("No sentiment detected, skipping ...");
        collector.ack(tuple);
        return;
    }

    String sentimentClass = sentimentToClass[sentiment];
    sentimentPeriodCounter.increment(sentimentClass);
    collector.ack(tuple);
}

The mood we estimate by simple formula:

Mood=−2⋅count(VeryNeg)−count(Neg)+count(Pos)+2⋅count(VeryPos)count(VeryNeg)+count(Neg)+count(Pos)+count(VeryPos)

where all counts are calculated for the desired period.

As soon as the Mood vales has been calculated, we can assign a sentiment class:

MoodEstimatorBolt.java
/**
 * Calculate mood value based on period counts.
 * The algorithm is quite simple, just calculate mood by formula
 * (-2 * VeryNeg - Neg + Pos + 2 * VeryPos) / total
 *
 * If counts empty or null, this method returns null, otherwise dict with values
 *
 * @param  counts  dict with sentiment values
 * @return         mood dict
 */
private Map<String, Object> calculateMood(Map<String, Integer> counts) {
    if(counts.isEmpty()) {
        return null;
    }

    float moodValue = 0;
    int total = 0;
    if(counts.containsKey("VeryNegative")) {
        moodValue -= 2 * counts.get("VeryNegative");
        total += counts.get("VeryNegative");
    }
    if(counts.containsKey("Negative")) {
        moodValue -= counts.get("Negative");
        total += counts.get("Negative");
    }
    if(counts.containsKey("Neutral")) {
        total += counts.get("Neutral");
    }
    if(counts.containsKey("Positive")) {
        moodValue += counts.get("Positive");
        total += counts.get("Positive");
    }
    if(counts.containsKey("VeryPositive")) {
        moodValue += 2 * counts.get("VeryPositive");
        total += counts.get("VeryPositive");
    }

    if(total > 0) {
        moodValue /= total;
    }

    String moodClass;
    if(moodValue > 0.05) {
        moodClass = new String("pos");
    }
    else if(moodValue < -0.05) {
        moodClass = new String("neg");
    }
    else {
        moodClass = new String("neu");
    }

    Map<String, Object> mood = new HashMap<String, Object>();
    mood.put("moodValue", moodValue);
    mood.put("moodClass", moodClass);
    return mood;
}
ESWriterBolt.java
@Override
public void execute(Tuple tuple) {
    final Map<String, Object> item = (HashMap<String, Object>) tuple.getValueByField("item");
    final String itemType = (String) tuple.getValueByField("period");
    final Date date = (Date) tuple.getValueByField("date");

    Map<String, Object> esItem = getESItem(item, date);
    try {
        IndexResponse response = client.prepareIndex(indexName, itemType)
            .setSource(esItem)
            .execute()
            .actionGet();
    } catch (Exception e) {
        collector.fail(tuple);
        log.warn("Index request failed ...");
        log.warn(e.getMessage());
        return;
    }

    collector.ack(tuple);
}

Versions

References

  1. Apache Storm is a free and open source distributed realtime computation system.
  2. Manning, Christopher D., Surdeanu, Mihai, Bauer, John, Finkel, Jenny, Bethard, Steven J., and McClosky, David. 2014. The Stanford CoreNLP Natural Language Processing Toolkit. In Proceedings of 52nd Annual Meeting of the Association for Computational Linguistics: System Demonstrations, pp. 55-60.