Google Analytics API deviceCategory

2020-04-16 02:48发布

问题:

I am trying to use the Google Analytics API (v3) in Google Scripts to pull Device Category information from Google Analytics.

Within Analytics under Audience -> Mobile -> Overview there is a Device Category section listing 'tablet', 'mobile' and 'desktop'. I wish to pull these numbers into a Google Sheet that my script is attached to.

The code I believe I should be using is: ga:deviceCategory==mobile (to pull mobile traffic) and ga:deviceCategory==tablet to pull tablet traffic.

However, I receive the error:

Invalid dimension or metric: ga:deviceCategory==desktop

I'm somewhat confused by this as Google's own documentation says that deviceCategory is a valid dimension

(https://developers.google.com/analytics/devguides/reporting/core/dimsmets#view=detail&group=platform_or_device&jump=ga_devicecategory)

If I remove the device type from the end ('ga:deviceCategory') I get the error:

Unknown metric(s): ga:deviceCategory (line 43, file "Code")

This leads me to believe that I need to include the metric (which I believe is 'pageviews') beforehand. If this is the case, can someone show me how I pull in the figures for mobile/tablet traffic?

I am having no other issues pulling other aspects of my data. For example:

var impressions = Analytics.Data.Ga.get(tableId, startDate, endDate, 'ga:visits').rows.toString(); 

works fine.

For reference, this is the full code I am using for device Category:

  // Get Mobile Visits, this is the number of visits from mobile devices
  var mvisits = Analytics.Data.Ga.get(tableId, startDate, endDate, 'ga:deviceCategory==mobile').rows.toString();
      mvisits = mvisits;

I would be grateful for any assistance and please let me know if you require any more code from my script.

Thanks in advance.

回答1:

My app script is a bit rusty but your problem is your == the dimension field is just a column you want to select.

var tableId  = 'ga:' + profileId;
var metric = 'ga:visits';
var options = {
    'dimensions': 'ga:deviceCategory',
    'filters': 'ga:deviceCategory==mobile'
    };
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
  options);

What you need to do is add some filters instead. If you think of this like a relational database this would be like saying

select deviceCategory, visits
from tableId  
where devicecategory == mobile

Remember you need to add a metric.

Example: shamelessly ripped from Analytics service page.