Search code examples
.netgoogle-analytics-api

Set MetricAggregations with Google Analytics Api


I code in C# and use Google.Analytics.Data.V1Beta library to retrieve GA4 data.

The query I would like to send to the api is the following :

{
"dimensions": [
    {
        "name": "pageLocation"
    }
],
"metrics": [
    {
        "name": "screenPageViews"
    }
],
"dateRanges": [
    {
        "startDate": "2022-01-01",
        "endDate": "2022-07-19"
    }
],
"dimensionFilter": {
    "filter": {
        "stringFilter": {
            "matchType": "PARTIAL_REGEXP",
            "value": "l-\\d{6,}"
        },
        "fieldName": "pageLocation"
    }
},
"limit": "1",
"metricAggregations": [
    "TOTAL"
]}

The important part of the query is the metricAggregations property. Here is my code

var request = new RunReportRequest
  {
    Property = "properties/" + myPropertyId,
    Dimensions = {
      new Dimension { Name = "pageLocation" }
    },
    DimensionFilter = new FilterExpression
    {
      Filter = new Filter
      {
        StringFilter = new Filter.Types.StringFilter { 
          CaseSensitive = true, 
          MatchType = Filter.Types.StringFilter.Types.MatchType.PartialRegexp, 
          Value = @"l-\d{6,}" 
        },
        FieldName = "pageLocation"
      }
    },
    Metrics = {
      new Metric { Name = "screenPageViews" }
    },
    MetricAggregations=new Google.Protobuf.Collections.RepeatedField<MetricAggregation> { MetricAggregation.Total},
    DateRanges = {
      new DateRange {
        StartDate = "2022-01-01",
        EndDate = "2022-07-19"
      }
    },
  };

  // Make the request
  var response = await _client.RunReportAsync(request);

The problem is that MetricAggregations property is a readonly property so it raises an error.

The error displayed is "Aggregation of metrics. Aggregated metric values will be shown in rows where the dimensionValues are set to "RESERVED_(MetricAggregation)".

Can somebody tell me how I can set this parameter with c# library ?

Regards


Solution

  • Hopefully I found the answer.

    To fill the MetricAggregations property, once your request object is created, you just need to call the Add method of this property.

    In my case :

    request.MetricAggregations.Add(MetricAggregation.Total );