Created
June 2, 2016 15:40
-
-
Save chipoglesby/eb9a9889375e1ac02663e1960a61361e to your computer and use it in GitHub Desktop.
Send your Google Analytics metrics and dimensions to Google Big Query using Google Apps Script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Replace xxx with your values as necessary. | |
function googleAnalyticsReporting() { | |
projectId = "xxx"; | |
datasetId = "xxx"; | |
tableId = 'xxx'; | |
data = []; | |
yesterday = new Date(); | |
yesterday.setDate(yesterday.getDate() - 1); | |
yesterday = Utilities.formatDate(yesterday, 'UTC', "yyyy-MM-dd"); | |
metrics = "ga:sessions, ga:users, ga:transactions,ga:transactionRevenue, ga:avgSessionDuration"; | |
options = {'dimensions': 'ga:date, ga:channelGrouping, ga:userType, ga:week, ga:year','sort': 'ga:date'}; | |
report = Analytics.Data.Ga.get("ga:xxx", yesterday, yesterday, metrics, options); | |
responseData = JSON.parse(report); | |
for (i in responseData.rows) { | |
final = JSON.stringify({ | |
'date': responseData.rows[i][0].replace(/(^[0-9]{4})([0-9]{2})([0-9]{2})/g,"$1-$2-$3T00:00:00Z"), | |
'channelGrouping': responseData.rows[i][1], | |
'userType': responseData.rows[i][2], | |
'week': responseData.rows[i][3], | |
'year': responseData.rows[i][4], | |
'sessions': responseData.rows[i][5], | |
'users': responseData.rows[i][6], | |
'transactions': responseData.rows[i][7], | |
'transactionRevenue': responseData.rows[i][8], | |
'avgSessionDuration': responseData.rows[i][9] | |
}); | |
data.push(final); | |
} | |
data = data.join("\n"); | |
blobData = Utilities.newBlob(data, "application/octet-stream"); | |
job = { | |
configuration: { | |
load: { | |
destinationTable: { | |
projectId: projectId, | |
datasetId: datasetId, | |
tableId: tableId | |
}, | |
sourceFormat: "NEWLINE_DELIMITED_JSON" | |
} | |
} | |
} | |
job = BigQuery.Jobs.insert(job, projectId, blobData); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment