node.jsgoogle-analyticsgoogle-analytics-apigoogle-analytics-4google-api-nodejs-client

Why my filters not working in the google analytics 4 app script code which I have written below? How can I fix it?



function runReport() {
  const propertyId = '359325548'; // Your GA4 property ID

  try {
    // Metrics
    const sessionsMetric = AnalyticsData.newMetric();
    sessionsMetric.name = 'sessions';
    
    const transactionsMetric = AnalyticsData.newMetric();
    transactionsMetric.name = 'transactions';
    
    const revenueMetric = AnalyticsData.newMetric();
    revenueMetric.name = 'purchaseRevenue';
    
    const engagementRateMetric = AnalyticsData.newMetric();
    engagementRateMetric.name = 'engagementRate';
    
    const bounceRateMetric = AnalyticsData.newMetric();
    bounceRateMetric.name = 'bounceRate';
    
    const totalUsersMetric = AnalyticsData.newMetric();
    totalUsersMetric.name = 'totalUsers';
    
    const engagedSessionsMetric = AnalyticsData.newMetric();
    engagedSessionsMetric.name = 'engagedSessions';
    
    const averagePurchaseRevenueMetric = AnalyticsData.newMetric();
    averagePurchaseRevenueMetric.name = 'averagePurchaseRevenue';
    
    // Dimension
    const deviceCategoryDimension = AnalyticsData.newDimension();
    deviceCategoryDimension.name = 'deviceCategory';

    // Date range
    const dateRange = AnalyticsData.newDateRange();
    dateRange.startDate = '2023-03-31';
    dateRange.endDate = 'today';

    // Country dimension filter
    const countryDimensionFilter = AnalyticsData.newFilter();
    Logger.log(countryDimensionFilter);
    countryDimensionFilter.fieldName = 'country';
    countryDimensionFilter.stringFilter = AnalyticsData.newStringFilter();
    countryDimensionFilter.stringFilter.value = 'Australia';
    Logger.log(countryDimensionFilter);
    
    const request = AnalyticsData.newRunReportRequest();
    request.dimensions = [deviceCategoryDimension];
    request.metrics = [sessionsMetric, transactionsMetric, revenueMetric, engagementRateMetric, bounceRateMetric, totalUsersMetric, engagedSessionsMetric, averagePurchaseRevenueMetric];
    request.dateRanges = [dateRange];
    request.dimensionFilter = countryDimensionFilter; // Adjusted to use dimensionFilter

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

    const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = spreadsheet.getSheetByName("device");
    
    // If the sheet doesn't exist, create a new one
    if (!sheet) {
      sheet = spreadsheet.insertSheet("device");
    } else {
      // Clear existing data if the "device" sheet already exists
      sheet.clear();
    }

    // Append the headers
    const headers = report.dimensionHeaders.concat(report.metricHeaders).map(header => header.name);
    sheet.appendRow(headers);

    // Append the results
    const rows = report.rows.map(row => {
      const dimensionValues = row.dimensionValues.map(value => value.value);
      const metricValues = row.metricValues.map(value => value.value);
      return dimensionValues.concat(metricValues);
    });

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

    console.log('Data saved to "device" tab.');
  } catch (e) {
    console.log('Error:', e);
  }
}

I am running this code but it gives me below error. Help me fix it please?:

Error: { [GoogleJsonResponseException: API call to analyticsdata.properties.runReport failed with error: Invalid JSON payload received. Unknown name "fieldName" at 'dimension_filter': Cannot find field. Invalid JSON payload received. Unknown name "stringFilter" at 'dimension_filter': Cannot find field.] details: { message: 'Invalid JSON payload received. Unknown name "fieldName" at 'dimension_filter': Cannot find field.Invalid JSON payload received. Unknown name "stringFilter" at 'dimension_filter': Cannot find field.', code: 400 }, name: 'GoogleJsonResponseException' }


Solution

  • Try to adapt something like this:

    const dimensionfilter = AnalyticsData.newFilterExpression()
    dimensionfilter.filter = AnalyticsData.newFilter()
    dimensionfilter.filter.fieldName = 'country'
    dimensionfilter.filter.stringFilter = AnalyticsData.newStringFilter()
    dimensionfilter.filter.stringFilter.value = 'Italy'