Platinum Partner
news,architects,bigdata,sql server,hadoop,twitter,azure

How I Got Twitter Data Onto SQL Server

I’ve been looking at how it might be possible to bring data from Twitter into SQL Server.

You might ask, Why ????

Well, why not ? It’s more an exercise in how this could be done using tools that are available.

There are several steps that I went through, and I’m pretty sure there may be a better way, and if you can think of any improvements, then feel free to use the comments section below.

Step 1 – Getting the Tweets

First up, we need to get the Twitter data. There are numerous ways to do this, however, the easiest way I’ve found is to use a product called cURL (available here: http://curl.haxx.se/download.html).

I saw this referenced while investigating the Microsoft Hadoop on Azure site (https://www.windowsazure.com/en-us/develop/net/tutorials/hadoop-social-web-data/) which was used to extract data to feed into a Hive database.

There are three parts to obtaining the Twitter data using cURL.

Part 1 – Get cURL, you can download this using the link above. I used the Win64 Binary SSL version.

Part 2 – Create a parameters file. As the MS link above shows, the parameters file acts as a filter to get the data you want from the Twitter feed. While it is possible to filter the data by hashtags, I wanted to get a more generalised set of data. To do this, I put the following filter in the parameters file. This effectively filters the data by any tweets that are geotagged.

locations=-180,-90,180,90

Part 3 – Create a batch file to run the job. The batch file created is effectively the same as the one referenced in the MS link. The file is called GetTwitterStream.cmd, and contains the following text. You need to replace <twitterusername> and <twitterpassword> with your twitter credentials.

curl -d @twitter_params.txt -k https://stream.twitter.com/1/statuses/filter.json –u<twitterusername>:<twitterpassword> >>twitter_stream_seq.txt

When you run the GetTwitterStream.cmd file, it starts cURL and starts getting data from the public Twitter streaming API, as shown below.

image

This gives us a file containing the JSON feed from Twitter.

Step 2 – Load the Twitter JSON Data into SQL

Next we need to get the JSON data from Twitter into SQL. I created a Load table for this, with the following structure:

CREATE TABLE [dbo].[TweetJSON](
[JSONData] [varchar](8000) NULL,
[ID] [int] IDENTITY(1,1) NOT NULL,
[Processed] [char](1) NULL
) ON [PRIMARY]

Then, we can load the JSON file created from cURL in step 1, using BULK INSERT. We need a Format file for this, shown below, and called BIFormatFile.txt

9.0
1
1 SQLCHAR 0 8000 “\r\n” 1 [JSONData] “”

The data can then be loaded using this Bulk Insert task:

BULK INSERT [dbo].[TweetJSON]
from ‘c:\BigData\TwitterData\twitter_stream_seq.txt’
with (CODEPAGE=’RAW’, FORMATFILE=’C:\BigData\twitterdata\BIFormatFile.txt’)

So now, we have a table with the JSON data in, and an Identity column to give us an ID we can reference.

Step 3 – Parse the JSON

Phil Factor has written a great article (here http://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/), which covers parsing JSON in T-SQL. I used the parseJSON function from this article, to extract the required fields from the Load table.

I created a staging table:

CREATE TABLE [dbo].[TweetJSONStaging](
    [Country] [varchar](200) NULL,
    [id_str] [varchar](200) NULL,
    [followers_count] [int] NULL,
    [profile_image_url] [varchar](200) NULL,
    [statuses_count] [int] NULL,
    [profile_background_image_url] [varchar](200) NULL,
    [created_at] [datetime] NULL,
    [friends_count] [int] NULL,
    [location] [varchar](200) NULL,
    [name] [varchar](200) NULL,
    [lang] [varchar](200) NULL,
    [screen_name] [varchar](200) NULL,

    [varchar](200) NULL,
    [geo_lat] [varchar](200) NULL,
    [geo_long] [varchar](200) NULL
    ) ON [Staging]

Then used the following process to iterate through the data and get it into the right format. The process followed here is to create a Cursor (I’ll get to this in a minute) with the records to change, and call the ParseJSON function against it to split the fields out, then to get the fields we want and insert them into a table. Next we set the Processed flag, and repeat the process till there are no more records to process.

declare @JSON NVARCHAR(MAX), @ID int

    declare jsCursor CURSOR FOR
    select JSONData, ID from tweetJson where Processed is null

    open jsCursor

    FETCH NEXT from jsCursor into @JSON, @ID
    while @@FETCH_STATUS=0
    BEGIN
    begin try
    insert into TweetJSONStaging ( Country, id_str, followers_count,
    profile_image_url,statuses_count,profile_background_image_url,created_at,
    friends_count,location,name,lang, screen_name, source, geo_lat, geo_long)
    select
    max(case when NAME=’country’ then StringValue end) as Country,
    max(case when NAME=’id_str’ then StringValue end) as id_str,
    max(case when NAME=’followers_count’ then convert (int,StringValue) end)
    as followers_count,
    max(case when NAME=’profile_image_url’ then StringValue end)
    as profile_image_url,
    max(case when NAME=’statuses_count’ then convert(int,StringValue) end)
    as statuses_count,
    max(case when NAME=’profile_background_image_url’ then StringValue end)
    as profile_background_image_url,
    max(case when NAME=’created_at’ then convert(datetime,
    (substring (StringValue,9,2)+’ ‘+substring (StringValue,5,3)+’ ‘+
    substring (StringValue,27,4) +’ ‘+substring (StringValue,12,2) +’:'+
    substring (StringValue,15,2)+’:'+substring (StringValue,18,2) ) ) end)
    as created_at,
    max(case when NAME=’friends_count’ then convert(int,StringValue) end)
    as friends_count,
    max(case when NAME=’location’ then StringValue end) as location,
    max(case when NAME=’name’ then StringValue end) as name,
    max(case when NAME=’lang’ then StringValue end) as lang,
    max(case when NAME=’screen_name’ then StringValue end) as screen_name,
    max(case when NAME=’source’ then StringValue end) as source,
    max(case when element_id=’1′ then StringValue end) as geo_lat,
    max(case when element_id=’2′ then StringValue end) as geo_long
    from dbo.parseJSON( @JSON)

    update tweetJSON
    set Processed = ‘Y’
    where ID=@ID

    end try
    begin catch
    update tweetJSON
    set Processed = ‘X’
    where ID=@ID
    end catch
    FETCH NEXT from jsCursor into @JSON, @ID

    end
    close jsCursor
    deallocate jsCursor

To allow this process to run in a reasonable amount of time, I created a couple of indexes on the load table (tweetJSON). The indexes are on the ID field (Clustered Index) and on the Processed flag.

CREATE UNIQUE CLUSTERED INDEX CI_ID ON [dbo].[TweetJSON]
    ( [ID] ASC ) ON [PRIMARY]

    CREATE NONCLUSTERED INDEX NCI_Processed ON [dbo].[TweetJSON]
    ( [Processed] ASC ) ON [PRIMARY]

Running this process took approx. 26 seconds to load 1000 records, so approx. 38 records a second.

So, I thought I’d try it with a While clause, rather than a cursor, and interestingly, it took the same amount of time to run, for 1000 records.

Update: As raised by Dave Ballantyne (@davebally), this shows that a While clause is effectively doing the same as the Cursor, since the process is still running over records one by one. (Further information can be found here).

declare @JSON varchar(8000), @ID int, @count int

    while 1=1
    BEGIN
    select top 1 @JSON = JSONData, @ID=ID from tweetJson where Processed =’N’
    begin try
    insert into TweetJSONStaging ( Country, id_str, followers_count,
    profile_image_url,statuses_count,profile_background_image_url,created_at,
    friends_count,location,name,lang, screen_name, source, geo_lat, geo_long)
    select
    max(case when NAME=’country’ then StringValue end) as Country,
    max(case when NAME=’id_str’ then StringValue end) as id_str,
    max(case when NAME=’followers_count’ then convert (int,StringValue) end)
    as followers_count,
    max(case when NAME=’profile_image_url’ then StringValue end)
    as profile_image_url,
    max(case when NAME=’statuses_count’ then convert(int,StringValue) end)
    as statuses_count,
    max(case when NAME=’profile_background_image_url’ then StringValue end)
    as profile_background_image_url,
    max(case when NAME=’created_at’ then convert(datetime,
    (substring (StringValue,9,2)+’ ‘+substring (StringValue,5,3)+’ ‘+
    substring (StringValue,27,4) +’ ‘+substring (StringValue,12,2) +’:'+
    substring (StringValue,15,2)+’:'+substring (StringValue,18,2) ) ) end)
    as created_at,
    max(case when NAME=’friends_count’ then convert(int,StringValue) end)
    as friends_count,
    max(case when NAME=’location’ then StringValue end) as location,
    max(case when NAME=’name’ then StringValue end) as name,
    max(case when NAME=’lang’ then StringValue end) as lang,
    max(case when NAME=’screen_name’ then StringValue end) as screen_name,
    max(case when NAME=’source’ then StringValue end) as source,
    max(case when element_id=’1′ then StringValue end) as geo_lat,
    max(case when element_id=’2′ then StringValue end) as geo_long
    from dbo.parseJSON( @JSON)

    update tweetJSON
    set Processed = ‘Y’
    where ID=@ID

    end try
    begin catch
    update tweetJSON
    set Processed = ‘X’
    where ID=@ID
    end catch

    select @count=count(1) from tweetJson where Processed =’N’

    if @count=0
    break
    else
    continue
    end

Thanks for reading! I’ll add an update when I’ve made changes to make it more performant.

 

 

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}