DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. How I Got Twitter Data Onto SQL Server

How I Got Twitter Data Onto SQL Server

Nick Haslam user avatar by
Nick Haslam
·
Jul. 25, 12 · Interview
Like (0)
Save
Tweet
Share
15.27K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Data (computing) twitter sql Database

Published at DZone with permission of Nick Haslam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • Top Three Docker Alternatives To Consider
  • The Quest for REST
  • How To Create and Edit Excel XLSX Documents in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: