SlideShare uma empresa Scribd logo
1 de 16
Baixar para ler offline
do something useful with 
Apps Script in 5 minutes 
5. Analytics pageviews to a sheet 
Bruce McPherson 
www.mcpher.com
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
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
Add analytics service 
in advanced services, enable analytics
Enable analytics on cloud console
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 
}
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'} ); 
}); 
}
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'); 
}
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()); 
}
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; 
},{}); 
}) 
}
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)) ; 
}); 
}
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);
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); 
}
take a look at the sheet 
You’ll find a row for each url in your site
Further homework 
● The problem is that Analytics treats each url 
variation as different URL - see below. How 
about modifying to combine ‘like’ urls
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

Mais conteúdo relacionado

Mais procurados

Do something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilterDo something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilterBruce McPherson
 
Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Bruce McPherson
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 
Introduction tomongodb
Introduction tomongodbIntroduction tomongodb
Introduction tomongodbLee Theobald
 
Data visualization by Kenneth Odoh
Data visualization by Kenneth OdohData visualization by Kenneth Odoh
Data visualization by Kenneth Odohpyconfi
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineJason Terpko
 
Testowanie JavaScript
Testowanie JavaScriptTestowanie JavaScript
Testowanie JavaScriptTomasz Bak
 
第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」
第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」
第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」Tsuyoshi Yamamoto
 
Improving Performance and Flexibility of Content Listings Using Criteria API
Improving Performance and Flexibility of Content Listings Using Criteria APIImproving Performance and Flexibility of Content Listings Using Criteria API
Improving Performance and Flexibility of Content Listings Using Criteria APINils Breunese
 
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! GrailsプラグインTsuyoshi Yamamoto
 
Visdjango presentation django_boston_oct_2014
Visdjango presentation django_boston_oct_2014Visdjango presentation django_boston_oct_2014
Visdjango presentation django_boston_oct_2014jlbaldwin
 

Mais procurados (20)

Dbabstraction
DbabstractionDbabstraction
Dbabstraction
 
Do something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilterDo something in 5 with apps scripts number 6 - fusion crossfilter
Do something in 5 with apps scripts number 6 - fusion crossfilter
 
Goa tutorial
Goa tutorialGoa tutorial
Goa tutorial
 
Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2Do something in 5 with gas 9-copy between databases with oauth2
Do something in 5 with gas 9-copy between databases with oauth2
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 
Database c# connetion
Database c# connetionDatabase c# connetion
Database c# connetion
 
Data backup
Data backupData backup
Data backup
 
Introduction tomongodb
Introduction tomongodbIntroduction tomongodb
Introduction tomongodb
 
Data visualization by Kenneth Odoh
Data visualization by Kenneth OdohData visualization by Kenneth Odoh
Data visualization by Kenneth Odoh
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation Pipeline
 
Testowanie JavaScript
Testowanie JavaScriptTestowanie JavaScript
Testowanie JavaScript
 
第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」
第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」
第3回Grails/Groovy勉強会名古屋「Grails名古屋座談会」
 
Improving Performance and Flexibility of Content Listings Using Criteria API
Improving Performance and Flexibility of Content Listings Using Criteria APIImproving Performance and Flexibility of Content Listings Using Criteria API
Improving Performance and Flexibility of Content Listings Using Criteria API
 
KMI System
KMI SystemKMI System
KMI System
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
 
RxSubject And Operators
RxSubject And OperatorsRxSubject And Operators
RxSubject And Operators
 
Bulk copy
Bulk copyBulk copy
Bulk copy
 
Fetch data from form
Fetch data from formFetch data from form
Fetch data from form
 
Visdjango presentation django_boston_oct_2014
Visdjango presentation django_boston_oct_2014Visdjango presentation django_boston_oct_2014
Visdjango presentation django_boston_oct_2014
 

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

Bubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsBubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsStefan Urbanek
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsLudmila Nesvitiy
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出Ymow Wu
 
Utilising the data attribute
Utilising the data attributeUtilising the data attribute
Utilising the data attributeRichard Martens
 
Data visualization in python/Django
Data visualization in python/DjangoData visualization in python/Django
Data visualization in python/Djangokenluck2001
 
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and SimpleDrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and SimpleAlexander Varwijk
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices -  Michael HacksteinNoSQL meets Microservices -  Michael Hackstein
NoSQL meets Microservices - Michael Hacksteindistributed matters
 
Experience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsExperience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsCédric Hüsler
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript CodeSuresh Balla
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptMohd Saeed
 
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docx
!  Modernizr v2.0.6  httpwww.modernizr.com   Copyri.docx!  Modernizr v2.0.6  httpwww.modernizr.com   Copyri.docx
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docxMARRY7
 

Semelhante a Do something useful in Apps Script 5. Get your analytics pageviews to a spreadhseet (20)

Bubbles – Virtual Data Objects
Bubbles – Virtual Data ObjectsBubbles – Virtual Data Objects
Bubbles – Virtual Data Objects
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Protractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applicationsProtractor framework – how to make stable e2e tests for Angular applications
Protractor framework – how to make stable e2e tests for Angular applications
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出
 
Utilising the data attribute
Utilising the data attributeUtilising the data attribute
Utilising the data attribute
 
Data visualization in python/Django
Data visualization in python/DjangoData visualization in python/Django
Data visualization in python/Django
 
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and SimpleDrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices -  Michael HacksteinNoSQL meets Microservices -  Michael Hackstein
NoSQL meets Microservices - Michael Hackstein
 
Google charts
Google chartsGoogle charts
Google charts
 
JQuery Flot
JQuery FlotJQuery Flot
JQuery Flot
 
Experience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - HighlightsExperience Manager 6 Developer Features - Highlights
Experience Manager 6 Developer Features - Highlights
 
Drupal 7 database api
Drupal 7 database api Drupal 7 database api
Drupal 7 database api
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript Code
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascript
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Intro to Ember.JS 2016
Intro to Ember.JS 2016Intro to Ember.JS 2016
Intro to Ember.JS 2016
 
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docx
!  Modernizr v2.0.6  httpwww.modernizr.com   Copyri.docx!  Modernizr v2.0.6  httpwww.modernizr.com   Copyri.docx
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docx
 

Último

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Último (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

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

  • 1. do something useful with Apps Script in 5 minutes 5. Analytics pageviews to a sheet Bruce McPherson www.mcpher.com
  • 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. 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. Add analytics service in advanced services, enable analytics
  • 5. Enable analytics on cloud console
  • 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. 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. 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. 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. 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. 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. 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. 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. take a look at the sheet You’ll find a row for each url in your site
  • 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. 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