0

I am Kinda new to AppScript and wanted to know how I can add multiple dimensions and metrics to the code below as well as how the filtering works. Your help is much appreciated.

Here is my reference and sample code:https://developers.google.com/apps-script/advanced/analyticsdata

1

1 Answer 1

1

Using the sample code from https://developers.google.com/apps-script/advanced/analyticsdata. Here is an example how to add 'sessions' metric to the request:

function runReport() {
  const propertyId = 'YOUR-GA4-PROPERTY-ID';

  try {
    const metric = AnalyticsData.newMetric();
    metric.name = 'activeUsers';

// adding additional sessions metric

    const metric2 = AnalyticsData.newMetric();
    metric2.name = 'sessions';

    const dimension = AnalyticsData.newDimension();
    dimension.name = 'city';

    const dateRange = AnalyticsData.newDateRange();
    dateRange.startDate = '2020-03-31';
    dateRange.endDate = 'today';

    const request = AnalyticsData.newRunReportRequest();
    request.dimensions = [dimension];
    
// add additional metric in the array

    request.metrics = [metric, metric2];
    request.dateRanges = dateRange;

    const report = AnalyticsData.Properties.runReport(request,
        'properties/' + propertyId);
    if (!report.rows) {
      Logger.log('No rows returned.');
      return;
    }

    const spreadsheet = SpreadsheetApp.create('Google Analytics Report');
    const sheet = spreadsheet.getActiveSheet();

    const dimensionHeaders = report.dimensionHeaders.map(
        (dimensionHeader) => {
          return dimensionHeader.name;
        });
    const metricHeaders = report.metricHeaders.map(
        (metricHeader) => {
          return metricHeader.name;
        });
    const headers = [...dimensionHeaders, ...metricHeaders];

    sheet.appendRow(headers);

    const rows = report.rows.map((row) => {
      const dimensionValues = row.dimensionValues.map(
          (dimensionValue) => {
            return dimensionValue.value;
          });
      const metricValues = row.metricValues.map(
          (metricValues) => {
            return metricValues.value;
          });
      return [...dimensionValues, ...metricValues];
    });

    sheet.getRange(2, 1, report.rows.length, headers.length)
        .setValues(rows);

    Logger.log('Report spreadsheet created: %s',
        spreadsheet.getUrl());
  } catch (e) {
    Logger.log('Failed with error: %s', e.error);
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.