Search code examples
google-apps-scriptgoogle-apigoogle-analytics-apigoogle-analytics-4

How To use FilterExpression in Google Analytics Data API in Google Apps Script


I'm trying to use the new Google Analytics Data API to pull in some very simple data from our GA4 property and into a spreadsheet.

This all works great.

However I now want to apply some Dimension Filters so that It returns only those rows that match the filter.

This is the code I've added but I think the format is wrong.

const dimensionfilter = AnalyticsData.newFilterExpression();
dimensionfilter.filter.fieldName = 'pageTitle';
dimensionfilter.filter.stringFilter.value = 'MYPAGETITLETEXT';

There are no examples in Apps script for adding DimensionFilter etc

Has anyone done this? Has anyone got any very simple examples.

Many thanks in advance.

Here is my full code

   function runReport() {
  const propertyId = '29045017783';

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


    const pagetitle = AnalyticsData.newDimension();
    pagetitle.name = 'pageTitle';

    const pagepath = AnalyticsData.newDimension();
    pagepath.name = 'pagePath';

    const dateRange = AnalyticsData.newDateRange();
    dateRange.startDate = '2022-05-01';
    dateRange.endDate = 'today';


    const dimensionfilter = AnalyticsData.newFilterExpression();
    dimensionfilter.filter.fieldName = 'pageTitle';
    dimensionfilter.filter.stringFilter.value = 'MYPAGETITLETEXT';


   

    const request = AnalyticsData.newRunReportRequest();
    request.dimensions = [pagetitle, pagepath];
    request.metrics = [metric];
    request.dateRanges = dateRange;
    request.limit=10;
    request.dimensionFilter = dimensionfilter;

    const report = AnalyticsData.Properties.runReport(request,'properties/' + propertyId);

    if (!report.rows) {
      Logger.log('No rows returned.');
      return;
    }

    const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    const sheet = spreadsheet.getActiveSheet();

    // Append the headers.
    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);

    // Append the results.
    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) {
    // TODO (Developer) - Handle exception
    Logger.log('Failed with error: %s', e.error);
  }
}

Solution

  • This is how you can apply Dimension Filter

    const dimensionfilter = AnalyticsData.newFilterExpression()
    dimensionfilter.filter = AnalyticsData.newFilter()
    dimensionfilter.filter.fieldName = 'pageTitle'
    dimensionfilter.filter.stringFilter = AnalyticsData.newStringFilter()
    dimensionfilter.filter.stringFilter.value = 'MYPAGETITLETEXT'
    

    Edit: For multiple filters

    To combine multiple filters with OR condition

    const pageTitles = [
      'MYPAGETITLETEXT1',
      'MYPAGETITLETEXT2'
    ]
    
    const dimensionfilter = AnalyticsData.newFilterExpression()
    dimensionfilter.orGroup = AnalyticsData.newFilterExpressionList()
    dimensionfilter.orGroup.expressions = []
    
    for (const pageTitle of pageTitles) {
      const filterExpression = AnalyticsData.newFilterExpression()
      filterExpression.filter = AnalyticsData.newFilter()
      filterExpression.filter.fieldName = 'pageTitle'
      filterExpression.filter.stringFilter = AnalyticsData.newStringFilter()
      filterExpression.filter.stringFilter.value = pageTitle
      dimensionfilter.orGroup.expressions.push(filterExpression)
    }
    

    You can refer to this document to understand How method signatures are determined