Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Do something useful in Apps Script 5. Get your analytics pageviews to a spreadhseet

4,989 views

Published on

Here's how to build on previous tutorials to get your Google Analytics PageView data into a Spreadsheet.

Published in: Technology
  • Be the first to comment

Do something useful in Apps Script 5. Get your analytics pageviews to a spreadhseet

  1. 1. do something useful with Apps Script in 5 minutes 5. Analytics pageviews to a sheet Bruce McPherson www.mcpher.com
  2. 2. Snippet objectives ● Use the lessons learned in ‘using a spreadsheet as a database’ ● Use the lessons learned in ‘getting analytics properties to a sheet’, and get the analytics id you want to analyze ● Flattens analytics data and writes it all to a sheet Libraries used ● database abstraction ● driver sheet ● useful stuff
  3. 3. Add libraries to script ● create a spreadsheet ● get its id ● create a script ● Open resources ● Add references to libraries Mrckbr9_w7PCphJtOzhzA_Cz3TLx7pV4j MHfCjPQlweartW45xYs6hFai_d-phDA33 Mcbr-v4SsYKJP7JMohttAZyz3TLx7pV4j
  4. 4. Add analytics service in advanced services, enable analytics
  5. 5. Enable analytics on cloud console
  6. 6. layout what you are going to do function myFunction() { // this is the propertyID we want to get the analytics for - it is the field named ‘id’ if you did the previous tutorial // open spreadsheet as database // get the analytics for all time // write to the sheet after deleting current contents }
  7. 7. write function to get pageviews First step - Create a function to get the pageviews from the Analytics service. The analytics service is rate limited, so we have to handle retries using exponential backoff. We’re only doing one call so its probably not needed, but no harm to get in the habit and create a reusable function. /** * get pageviews * @param {string} propertyId the analytics property id * @param {Date} start start date * @param {Date} finish end date * @return {object} Analytics response data **/ function pageViews (propertyId, start , finish) { return cUseful.rateLimitExpBackoff(function () { return Analytics.Data.Ga.get('ga:' + propertyId , gaDate(start), gaDate(finish), 'ga:pageViews', {dimensions:'ga:pagePath'} ); }); }
  8. 8. write function to format date The analytics service expects a specific date format for date range filtering. Create a reusable function for that. /** * convert date format for analytics filtering * @param {Date} a date * @return {string} a formatted date */ function gaDate (dt) { return Utilities.formatDate(dt, Session.getScriptTimeZone(), 'yyyy-MM-dd'); }
  9. 9. write wrapper to get data This fills in some default dates and gets the analytics data. However the data is not yet in a very usable format. /** * get analytics data * @param {string} propertyId the analytics property id * @param {Date} optStart start date * @param {Date} optEnd end date * @return {Array.objects} array of objects showing url and pageviews **/ function getAnalytics(propertyId,optStart,optEnd) { // get data for this property filtered by optional dates var data = pageViews (propertyId, optStart || new Date(2010,0 ,1 ), optEnd || new Date()); }
  10. 10. clean analytics data Clean up property names and convert to a usable JavaScript array function getAnalytics(propertyId,optStart,optEnd) { // get data for this property filtered by optional dates var data = pageViews (propertyId, optStart || new Date(2010,0 ,1 ), optEnd || new Date()); // clean up into a json object return data.rows.map ( function (row) { var i =0; return row.reduce(function (p,c) { p[data.columnHeaders[i++]['name'].replace("ga:","")] = c; return p; },{}); }) }
  11. 11. sort analytics data May as well also sort it by URL function getAnalytics(propertyId,optStart,optEnd) { // get data for this property filtered by optional dates var data = pageViews (propertyId, optStart || new Date(2010,0 ,1 ), optEnd || new Date()); // clean up into a json object return data.rows.map ( function (row) { var i =0; return row.reduce(function (p,c) { p[data.columnHeaders[i++]['name'].replace("ga:","")] = c; return p; },{}); }) .sort ( function (a,b) { return (a.pagePath > b.pagePath ? 1 : (a.pagePath === b.pagePath ? 0 : -1)) ; }); }
  12. 12. write everything to a sheet We’ve cleaned up the data so it can just be written as is // write to the sheet after deleting current contents var result = sheetHandle.remove(); if (result.handleCode < 0 ) throw JSON.stringify(result); var result = sheetHandle.save(data); if (result.handleCode < 0 ) throw JSON.stringify(result);
  13. 13. Here’s the whole thing function myFunction() { // this is the propertyID we want to get the analytics for var propertyId ='4xxx7'; // open spreadsheet as database var sheetHandle = new cDbAbstraction.DbAbstraction (cDriverSheet, { siloid:'analytics' + propertyId, dbid:'19tZRW5CxA4V0kjJX8yAXAGGjzvVZ1433vz-NmBIBt7U' }); if (!sheetHandle.isHappy()) throw 'unable to open sheet'; // get the analytics var data = getAnalytics (propertyId, new Date(2010,0,1), new Date()); // write to the sheet after deleting current contents var result = sheetHandle.remove(); if (result.handleCode < 0 ) throw JSON.stringify(result); var result = sheetHandle.save(data); if (result.handleCode < 0 ) throw JSON.stringify(result); }
  14. 14. take a look at the sheet You’ll find a row for each url in your site
  15. 15. Further homework ● The problem is that Analytics treats each url variation as different URL - see below. How about modifying to combine ‘like’ urls
  16. 16. Follow up materials Take a copy of this script Take a copy of these slides Join me on G+, or the G+ community More on desktop liberation More on database abstraction More on Analytics instrumentation More 5 minute things

×