SlideShare una empresa de Scribd logo
1 de 16
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Similar 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
 

Similar 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

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 

Último (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

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