샘플

컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.

이 도움말에서는 Google 애널리틱스 Reporting API v4 기능의 샘플을 제공합니다.

측정기준 및 측정항목

다음은 몇 가지 측정기준과 측정항목으로 구성된 간단한 요청입니다. 사용 가능한 전체 측정기준과 측정항목이 있는 경우 측정기준 및 측정항목 탐색기를 참고하세요. 측정기준과 측정항목은 POST 본문을 통해 전달되는 구성 가능한 반복 객체입니다.

자바

// Create the DateRange object.
DateRange dateRange = new DateRange();
dateRange.setStartDate("2015-06-15");
dateRange.setEndDate("2015-06-30");

// Create the Metrics object.
Metric sessions = new Metric()
    .setExpression("ga:sessions")
    .setAlias("sessions");

//Create the Dimensions object.
Dimension browser = new Dimension()
    .setName("ga:browser");

// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
    .setViewId("XXXX")
    .setDateRanges(Arrays.asList(dateRange))
    .setDimensions(Arrays.asList(browser))
    .setMetrics(Arrays.asList(sessions));

ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
requests.add(request);

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest()
    .setReportRequests(requests);

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.reports().batchGet(getReport).execute();

Python

response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
    {
      "viewId":"XXXX",
      "dateRanges":[
        {
          "startDate":"2015-06-15",
          "endDate":"2015-06-30"
        }],
      "metrics":[
        {
          "expression":"ga:sessions"
        }],
      "dimensions": [
        {
          "name":"ga:browser"
        }]
      }]
  }
).execute()

PHP

// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2015-06-15");
$dateRange->setEndDate("2015-06-30");

// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");

//Create the Dimensions object.
$browser = new Google_Service_AnalyticsReporting_Dimension();
$browser->setName("ga:browser");

// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("XXXX");
$request->setDateRanges($dateRange);
$request->setDimensions(array($browser));
$request->setMetrics(array($sessions));

$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analyticsreporting->reports->batchGet( $body );

자바스크립트

api.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
      {
        "startDate":"2015-06-15",
        "endDate":"2015-06-30"
      }],
    "metrics":[
      {
        "expression":"ga:sessions"
      }],
    "dimensions": [
      {
        "name":"ga:browser"
      }]
  }]
} ).execute(handleReportingResults)

C#

// Create the DateRange object.
DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

// Create the Metrics object.
Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };

//Create the Dimensions object.
Dimension browser = new Dimension { Name = "ga:browser" };

// Create the ReportRequest object.
// Create the ReportRequest object.
ReportRequest reportRequest = new ReportRequest
{
    ViewId = "XXXX",
    DateRanges = new List<DateRange>() { dateRange },
    Dimensions = new List<Dimension>() { browser },
    Metrics = new List<Metric>() { sessions }
};

List<ReportRequest> requests = new List<ReportRequest>();
requests.Add(reportRequest);

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
      {
        "startDate":"2015-06-15",
        "endDate":"2015-06-30"
      }],
    "metrics":[
      {
        "expression":"ga:sessions"
      }],
    "dimensions": [
      {
        "name":"ga:browser"
      }]
    }]
}

여러 기간

다음은 기간이 여러 개인 예입니다.

자바

// Create DateRange objects.
DateRange march = new DateRange()
    .setStartDate("2015-03-01")
    .setEndDate("2015-03-31");

DateRange january = new DateRange()
    .setStartDate("2015-01-01")
    .setEndDate("2015-01-31");

// Create the Metrics object.
Metric sessions = new Metric()
    .setExpression("ga:sessions")
    .setAlias("sessions");

// Create the Dimensions object.
Dimension browser = new Dimension()
    .setName("ga:browser");

// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
    .setViewId("XXXX")
    .setDateRanges(Arrays.asList(march, january))
    .setDimensions(Arrays.asList(browser))
    .setMetrics(Arrays.asList(sessions));

Python

response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
    {
      "viewId":"XXXX",
      "dateRanges":[
      {
        "startDate":"2015-01-01",
        "endDate":"2015-01-31"
      },
      {
        "startDate":"2015-03-01",
        "endDate":"2015-03-31"
      }],
      "dimensions":[
      {
        "name":"ga:browser"
      }],
      "metrics":[
      {
        "expression":"ga:sessions"
      }]
    }]
  }
).execute()

PHP

// Create DateRange objects.
$march = new Google_Service_AnalyticsReporting_DateRange();
$march->setStartDate("2015-03-01");
$march->setEndDate("2015-03-31");

$january = new Google_Service_AnalyticsReporting_DateRange();
$january->setStartDate("2015-01-01");
$january->setEndDate("2015-01-31");

...

// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("XXXX");
$request->setDateRanges(array($march, $january));
$request->setDimensions(array($browser));
$request->setMetrics(array($sessions));

자바스크립트

api.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "startDate":"2015-01-01",
      "endDate":"2015-01-31"
    },
    {
      "startDate":"2015-03-01",
      "endDate":"2015-03-31"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    }],
    "metrics":[
    {
      "expression":"ga:sessions"
    }]
  }]
} ).execute(handleReportingResults)

C#

// Create the DateRange object.
DateRange march = new DateRange() { StartDate = "2015-03-01", EndDate = "2015-03-31" };

DateRange january = new DateRange() { StartDate = "2015-01-01", EndDate = "2015-01-31" };

// Create the Metrics object.
Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };

//Create the Dimensions object.
Dimension browser = new Dimension { Name = "ga:browser" };

// Create the ReportRequest object.
// Create the ReportRequest object.
ReportRequest reportRequest = new ReportRequest
{
    ViewId = "XXXX",
    DateRanges = new List<DateRange>() { march, january },
    Dimensions = new List<Dimension>() { browser },
    Metrics = new List<Metric>() { sessions }
};

List<ReportRequest> requests = new List<ReportRequest>();
requests.Add(reportRequest);

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "startDate":"2015-01-01",
      "endDate":"2015-01-31"
    },
    {
      "startDate":"2015-03-01",
      "endDate":"2015-03-31"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    }],
    "metrics":[
    {
      "expression":"ga:sessions"
    }]
  }]
}

여러 기간으로 요청의 응답을 파싱하면 결과가 dateRangeValues의 배열로 반환됩니다.

자바

private static void printResults(List<Report> reports) {
  for (Report report : reports) {
    ColumnHeader header = report.getColumnHeader();
    List<String> dimensionHeaders = header.getDimensions();
    List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
    List<ReportRow> rows = report.getData().getRows();

    for (ReportRow row : rows) {
      List<String> dimensions = row.getDimensions();
      List<DateRangeValues> metrics = row.getMetrics();
      for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
        System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i));
      }

      for (int j = 0; j < metrics.size(); j++) {
        System.out.print("Date Range (" + j + "): ");
        DateRangeValues values = metrics.get(j);
        for (int k = 0; k < values.getValues().size() && k < metricHeaders.size(); k++) {
          System.out.println(metricHeaders.get(k).getName() + ": " + values.getValues().get(k));
        }
      }
    }
  }
}

Python

def printResults(response):
  for report in response.get("reports", []):
    columnHeader = report.get("columnHeader", {})
    dimensionHeaders = columnHeader.get("dimensions", [])
    metricHeaders = columnHeader.get("metricHeader", {}).get("metricHeaderEntries", [])
    rows = report.get("data", {}).get("rows", [])

    for row in rows:
      dimensions = row.get("dimensions", [])
      dateRangeValues = row.get("metrics", [])

      for header, dimension in zip(dimensionHeaders, dimensions):
        print header + ": " + dimension

      for i, values in enumerate(dateRangeValues):
        print "    Date range index: " + str(i)
        for metric, value in zip(metricHeaders, values.get("values")):
          print "    "  + metric.get("name") + ": " + value

PHP

function printResults(&$reports) {
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();

    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
      $metrics = $row->getMetrics();
      for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
        print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
      }

      for ($j = 0; $j < count($metrics); $j++) {
        $values = $metrics[$j]->getValues();
        for ($k = 0; $k < count($values); $k++) {
          $entry = $metricHeaders[$k];
          print($entry->getName() . ": " . $values[$k] . "\n");
        }
      }
    }
  }
}

자바스크립트

function handleReportingResults(response) {
  if (!response.code) {
    outputToPage('Query Success');
    for( var i = 0, report; report = response.reports[ i ]; ++i )
    {
      output.push('<h3>All Rows Of Data</h3>');
      if (report.data.rows && report.data.rows.length) {
        var table = ['<table>'];

        // Put headers in table.
        table.push('<tr><th>', report.columnHeader.dimensions.join('</th><th>'), '</th>');
        table.push('<th>Date range #</th>');

        for (var i=0, header; header = report.columnHeader.metricHeader.metricHeaderEntries[i]; ++i) {
          table.push('<th>', header.name, '</th>');
        }

        table.push('</tr>');

        // Put cells in table.
        for (var rowIndex=0, row; row = report.data.rows[rowIndex]; ++rowIndex) {
          for(var dateRangeIndex=0, dateRange; dateRange = row.metrics[dateRangeIndex]; ++dateRangeIndex) {
            // Put dimension values
            table.push('<tr><td>', row.dimensions.join('</td><td>'), '</td>');
            // Put metric values for the current date range
            table.push('<td>', dateRangeIndex, '</td><td>', dateRange.values.join('</td><td>'), '</td></tr>');
          }
        }
        table.push('</table>');

        output.push(table.join(''));
      } else {
        output.push('<p>No rows found.</p>');
      }
    }
    outputToPage(output.join(''));

  } else {
    outputToPage('There was an error: ' + response.message);
  }
}

C#

public static void printResults(List<Report> reports)
{
    foreach (Report report in reports)
    {
        ColumnHeader header = report.ColumnHeader;
        List<string> dimensionHeaders = (List<string>)header.Dimensions;

        List<MetricHeaderEntry> metricHeaders = (List<MetricHeaderEntry>)header.MetricHeader.MetricHeaderEntries;
        List<ReportRow> rows = (List<ReportRow>)report.Data.Rows;

        foreach (ReportRow row in rows)
        {
            List<string> dimensions = (List<string>)row.Dimensions;
            List<DateRangeValues> metrics = (List<DateRangeValues>)row.Metrics;

            for (int i = 0; i < dimensionHeaders.Count() && i < dimensions.Count(); i++)
            {
                Console.WriteLine(dimensionHeaders[i] + ": " + dimensions[i]);
            }

            for (int j = 0; j < metrics.Count(); j++)
            {
                Console.WriteLine("Date Range (" + j + "): ");
                DateRangeValues values = metrics[j];
                for (int k = 0; k < values.Values.Count() && k < metricHeaders.Count(); k++)
                {
                    Console.WriteLine(metricHeaders[k].Name + ": " + values.Values[k]);
                }
            }
        }
    }
}

출력 JSON

{
  "reports": [
    {
      "columnHeader": {
        "dimensions": [
          "ga:browser"
        ],
        "metricHeader": {
          "metricHeaderEntries": [
            {
              "name": "ga:sessions",
              "type": "INTEGER"
            }
          ]
        }
      },
      "data": {
        "rows": [
          {
            "dimensions": [
              "Firefox"
            ],
            "metrics": [
              {
                "values": [
                  "2161"
                ]
              },
              {
                "values": [
                  "2171"
                ]
              }
            ]
          },
          {
            "dimensions": [
              "Internet Explorer"
            ],
            "metrics": [
              {
                "values": [
                  "1705"
                ]
              },
              {
                "values": [
                  "2019"
                ]
              }
            ]
          },
        ],
        ...
      }
    }
  ]
}

측정항목 표현식

반복 측정항목 매개변수는 기존 측정항목을 사용할 수 있지만 기존 측정항목을 새 측정항목 표현식으로 결합하여 맞춤 계산된 측정항목을 만들 수도 있습니다. 아래 샘플은 나누기 작업이므로 formattingTypeFLOAT로 설정해야 합니다. 또한 alias 매개변수도 사용합니다.

자바

// Create the Metrics object.
Metric metricExpression = new Metric()
    .setExpression("ga:goal1Completions/ga:goal1Starts")
    .setFormattingType("FLOAT")
    .setAlias("Metric Expression");

Python

# Create the Metrics object.
metric_expression = {
  'expression': 'ga:goal1Completions/ga:goal1Starts',
  'formattingType': 'FLOAT',
  'alias': 'Metric Expression'
}

PHP

// Create the Metrics object.
$metric_expression = new Google_Service_AnalyticsReporting_Metric();
$metric_expression->setExpression("ga:goal1Completions/ga:goal1Starts");
$metric_expression->setFormattingType("FLOAT");
$metric_expression->setAlias("Metric Expression");

자바스크립트

gapi.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
    {

      ...

      "metrics":[
        {
          "expression":"ga:goal1Completions/ga:goal1Starts",
          "formattingType":"FLOAT",
         "alias":"Metric Expression"
       }]
    }
  ]
} ).execute(handleReportingResults)

C#

// Create the Metrics object.
Metric metricExpression = new Metric
{
    Expression = "ga:goal1Completions/ga:goal1Starts",
    FormattingType = "FLOAT",
    Alias = "Metric Expression"
};

JSON

"metrics":[
{
  "expression":"ga:goal1Completions/ga:goal1Starts",
  "formattingType":"FLOAT",
  "alias":"Metric Expression"
}]

히스토그램 버킷

API v4를 사용하면 클라이언트 측에서 값비싼 데이터 처리를 하지 않아도 되는 커스텀 히스토그램 버킷 세트를 정의할 수도 있습니다. 다음은 버킷화된 측정기준의 예입니다. 또한 버케팅된 측정기준을 올바른 순서로 정렬하는 orderBy 매개변수도 있습니다.

자바

// Create the Dimensions object.
Dimension buckets = new Dimension()
    .setName("ga:sessionCount")
    .setHistogramBuckets(Arrays.asList(1L,10L,100L,200L,300L,400L));

// Create the Ordering.
OrderBy ordering = new OrderBy()
    .setOrderType("HISTOGRAM_BUCKET")
    .setFieldName("ga:sessionCount");

Python

response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
    {
    "dateRanges": [
        {
            "endDate": "2015-11-30",
            "startDate": "2015-11-01"
        }
    ],
    "metrics": [
        {
            "expression": "ga:users"
        }
    ],
    "viewId": "XXXX",
    "dimensions":[
    {
      "name":"ga:sessionCount",
      "histogramBuckets":["1","10","100","200","400"]
    }],
    "orderBys":[
    {
      "fieldName":"ga:sessionCount",
      "orderType":"HISTOGRAM_BUCKET"
    }],
  }]
  }
).execute()

PHP

// Create the Dimensions object.
$buckets = new Google_Service_AnalyticsReporting_Dimension();
$buckets->setName("ga:sessionCount");
$buckets->setHistogramBuckets(array(1,10,100,200,300,400));

// Create the Ordering.
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setOrderType("HISTOGRAM_BUCKET");
$ordering->setFieldName("ga:sessionCount");

자바스크립트

 gapi.client.analyticsreporting.reports.batchGet( {
   "reportRequests":[
     {
       "dateRanges": [
         {
           "endDate": "2015-11-30",
           "startDate": "2015-11-01"
         }
       ],
       "metrics": [
         {
            "expression": "ga:users"
         }
       ],
      "viewId": "XXXX",
      "dimensions":[
      {
        "name":"ga:sessionCount",
        "histogramBuckets":["1","10","100","200","400"]
      }],
      "orderBys":[
      {
        "fieldName":"ga:sessionCount",
        "orderType":"HISTOGRAM_BUCKET"
      }],
     }]
 } ).execute(handleReportingResults)

C#

// Create the Dimensions object.
Dimension buckets = new Dimension
{
    Name = "ga:sessionCount",
    HistogramBuckets = (IList<long?>)new List<long> { 1L, 10L, 100L, 200L, 300L, 400L }
};

// Create the Ordering.
OrderBy ordering = new OrderBy()
{
    OrderType = "HISTOGRAM_BUCKET",
    FieldName = "ga:sessionCount"
};

JSON

{
  "reportRequests":[
  {
    "dateRanges": [
        {
            "endDate": "2014-11-30",
            "startDate": "2014-11-01"
        }
    ],
    "metrics": [
        {
            "expression": "ga:users"
        }
    ],
    "viewId": "XXXX",
    "dimensions":[
    {
      "name":"ga:sessionCount",
      "histogramBuckets":["1","10","100","200","400"]
    }],
    "orderBys":[
    {
      "fieldName":"ga:sessionCount",
      "orderType":"HISTOGRAM_BUCKET"
    }],
  }]
}

JSON 응답

{
    "reports": [
        {
            "columnHeader": {
                "dimensions": [
                    "ga:sessionCount"
                ],
                "metricHeader": {
                    "metricHeaderEntries": [
                        {
                            "name": "ga:users",
                            "type": "INTEGER"
                        }
                    ]
                }
            },
            "data": {
                "isDataGolden": true,
                "maximums": [
                    {
                        "values": [
                            "94"
                        ]
                    }
                ],
                "minimums": [
                    {
                        "values": [
                            "2"
                        ]
                    }
                ],
                "rowCount": 5,
                "rows": [
                    {
                        "dimensions": [
                            "1-9"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "94"
                                ]
                            }
                        ]
                    },
                    {
                        "dimensions": [
                            "10-99"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "21"
                                ]
                            }
                        ]
                    },
                    {
                        "dimensions": [
                            "100-199"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "57"
                                ]
                            }
                        ]
                    },
                    {
                        "dimensions": [
                            "200-399"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "20"
                                ]
                            }
                        ]
                    },
                    {
                        "dimensions": [
                            "400+"
                        ],
                        "metrics": [
                            {
                                "values": [
                                    "2"
                                ]
                            }
                        ]
                    }
                ],
                "totals": [
                    {
                        "values": [
                            "194"
                        ]
                    }
                ]
            }
        }
    ]
}

세그먼트

세그먼트는 세그먼트 필터 객체의 논리 연산자를 결합하여 정의됩니다. 또한 측정기준 목록에 ga:segment를 추가해야 합니다. 세그먼트 정의는 검색어 내에서 동적으로 구성되거나 기존 기본 제공/맞춤 세그먼트의 ID를 지정할 수 있습니다. 다음은 동적 세그먼트 정의를 사용한 예입니다.

자바

private static void segmentRequest(Analyticsreporting analyticsreporting) throws IOException {

  // Create the DateRange object.
  DateRange dateRange = new DateRange();
  dateRange.setStartDate("2015-06-15");
  dateRange.setEndDate("2015-06-30");

  // Create the Metrics object.
  Metric sessions = new Metric()
      .setExpression("ga:sessions")
      .setAlias("sessions");

  //Create the browser dimension.
  Dimension browser = new Dimension()
      .setName("ga:browser");

  // Create the segment dimension.
  Dimension segmentDimensions = new Dimension()
      .setName("ga:segment");

  // Create Dimension Filter.
  SegmentDimensionFilter dimensionFilter = new SegmentDimensionFilter()
      .setDimensionName("ga:browser")
      .setOperator("EXACT")
      .setExpressions(Arrays.asList("Safari"));

  // Create Segment Filter Clause.
  SegmentFilterClause segmentFilterClause = new SegmentFilterClause()
      .setDimensionFilter(dimensionFilter);

  // Create the Or Filters for Segment.
  OrFiltersForSegment orFiltersForSegment = new OrFiltersForSegment()
      .setSegmentFilterClauses(Arrays.asList(segmentFilterClause));

  // Create the Simple Segment.
  SimpleSegment simpleSegment = new SimpleSegment()
      .setOrFiltersForSegment(Arrays.asList(orFiltersForSegment));

  // Create the Segment Filters.
  SegmentFilter segmentFilter = new SegmentFilter()
      .setSimpleSegment(simpleSegment);

  // Create the Segment Definition.
  SegmentDefinition segmentDefinition = new SegmentDefinition()
      .setSegmentFilters(Arrays.asList(segmentFilter));

  // Create the Dynamic Segment.
  DynamicSegment dynamicSegment = new DynamicSegment()
      .setSessionSegment(segmentDefinition)
      .setName("Sessions with Safari browser");

  // Create the Segments object.
  Segment segment = new Segment()
      .setDynamicSegment(dynamicSegment);

  // Create the ReportRequest object.
  ReportRequest request = new ReportRequest()
      .setViewId("XXXX")
      .setDateRanges(Arrays.asList(dateRange))
      .setDimensions(Arrays.asList(browser, segmentDimensions))
      .setSegments(Arrays.asList(segment))
      .setMetrics(Arrays.asList(sessions));

  // Create the GetReportsRequest object.
  GetReportsRequest getReport = new GetReportsRequest()
      .setReportRequests(Arrays.asList(request));

  // Call the batchGet method.
  GetReportsResponse response = analyticsreporting.reports().batchGet(getReport)
      .execute();

  printResults(response.getReports());
}

Python

  response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name": "Sessions with Safari browser",
        "userSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":
              {
                "segmentFilterClauses": [
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "operator":"EXACT",
                    "expressions":["Safari"]
                  }
                }]
              }
            }
          }]
        }
      }
    }]
  }]
}).execute()

PHP

function segmentRequest(&$analyticsreporting) {

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("2015-06-15");
  $dateRange->setEndDate("2015-06-30");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  //Create the browser dimension.
  $browser = new Google_Service_AnalyticsReporting_Dimension();
  $browser->setName("ga:browser");

  // Create the segment dimension.
  $segmentDimensions = new Google_Service_AnalyticsReporting_Dimension();
  $segmentDimensions->setName("ga:segment");

  // Create Dimension Filter.
  $dimensionFilter = new Google_Service_AnalyticsReporting_SegmentDimensionFilter();
  $dimensionFilter->setDimensionName("ga:browser");
  $dimensionFilter->setOperator("EXACT");
  $dimensionFilter->setExpressions(array("Safari"));

  // Create Segment Filter Clause.
  $segmentFilterClause = new Google_Service_AnalyticsReporting_SegmentFilterClause();
  $segmentFilterClause->setDimensionFilter($dimensionFilter);

  // Create the Or Filters for Segment.
  $orFiltersForSegment = new Google_Service_AnalyticsReporting_OrFiltersForSegment();
  $orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));

  // Create the Simple Segment.
  $simpleSegment = new Google_Service_AnalyticsReporting_SimpleSegment();
  $simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));

  // Create the Segment Filters.
  $segmentFilter = new Google_Service_AnalyticsReporting_SegmentFilter();
  $segmentFilter->setSimpleSegment($simpleSegment);

  // Create the Segment Definition.
  $segmentDefinition = new Google_Service_AnalyticsReporting_SegmentDefinition();
  $segmentDefinition->setSegmentFilters(array($segmentFilter));

  // Create the Dynamic Segment.
  $dynamicSegment = new Google_Service_AnalyticsReporting_DynamicSegment();
  $dynamicSegment->setSessionSegment($segmentDefinition);
  $dynamicSegment->setName("Sessions with Safari browser");

  // Create the Segments object.
  $segment = new Google_Service_AnalyticsReporting_Segment();
  $segment->setDynamicSegment($dynamicSegment);

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId("XXXX");
  $request->setDateRanges(array($dateRange));
  $request->setDimensions(array($browser, $segmentDimensions));
  $request->setSegments(array($segment));
  $request->setMetrics(array($sessions));

  // Create the GetReportsRequest object.
  $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $getReport->setReportRequests(array($request));

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  $response = $analyticsreporting->reports->batchGet( $body );

  printResults($response->getReports());
}

자바스크립트

gapi.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name": "Sessions with Safari browser",
        "userSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":
              {
                "segmentFilterClauses": [
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "operator":"EXACT",
                    "expressions":["Safari"]
                  }
                }]
              }
            }
          }]
        }
      }
    }]
  }]
}).execute(handleReportingResults)

C#

// Create the DateRange object.
DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

// Create the Metrics object.
Metric sessions = new Metric() { Expression = "ga:sessions", Alias = "sessions" };

//Create the browser dimension.
Dimension browser = new Dimension() { Name = "ga:browser" };

// Create the segment dimension.
Dimension segmentDimensions = new Dimension() { Name = "ga:segment" };

// Create Dimension Filter.
SegmentDimensionFilter dimensionFilter = new SegmentDimensionFilter() { DimensionName = "ga:browser", Operator__ = "EXACT", Expressions = new List<string> { "Safari" } };

// Create Segment Filter Clause.
SegmentFilterClause segmentFilterClause = new SegmentFilterClause() { DimensionFilter = dimensionFilter };

// Create the Or Filters for Segment.
OrFiltersForSegment orFiltersForSegment = new OrFiltersForSegment() { SegmentFilterClauses = new List<SegmentFilterClause> { segmentFilterClause } };

// Create the Simple Segment.
SimpleSegment simpleSegment = new SimpleSegment() { OrFiltersForSegment = new List<OrFiltersForSegment> { orFiltersForSegment } };

// Create the Segment Filters.
SegmentFilter segmentFilter = new SegmentFilter() { SimpleSegment = simpleSegment };

// Create the Segment Definition.
SegmentDefinition segmentDefinition = new SegmentDefinition() { SegmentFilters = new List<SegmentFilter> { segmentFilter } };

// Create the Dynamic Segment.
DynamicSegment dynamicSegment = new DynamicSegment() { SessionSegment = segmentDefinition, Name = "Sessions with Safari browser" };

// Create the Segments object.
Segment segment = new Segment() { DynamicSegment = dynamicSegment };

// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
{
    ViewId = "XXXX",
    DateRanges = new List<DateRange> { dateRange },
    Dimensions = new List<Dimension> { browser, segmentDimensions },
    Segments = new List<Segment> { segment },
    Metrics = new List<Metric> { sessions }
};

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name": "Sessions with Safari browser",
        "userSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":
              {
                "segmentFilterClauses": [
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "operator":"EXACT",
                    "expressions":["Safari"]
                  }
                }]
              }
            }
          }]
        }
      }
    }]
  }]
}

위에서 언급했듯이 동적 세그먼트 정의를 구성하는 대신 세그먼트 정의의 segmentId 필드를 사용하여 사전 정의된 세그먼트 ID를 지정할 수 있습니다. 아래 예에서는 재사용자를 위한 세그먼트를 만듭니다.

자바

  // Create the Segments object for returning users.
  Segment segment = new Segment()
      .setSegmentId("gaid::-3");

  // Create the ReportRequest object.
  ReportRequest request = new ReportRequest()
      .setViewId("XXXX")
      .setDateRanges(Arrays.asList(dateRange))
      .setDimensions(Arrays.asList(browser, segmentDimensions))
      .setSegments(Arrays.asList(segment))
      .setMetrics(Arrays.asList(sessions));

  // Create the GetReportsRequest object.
  GetReportsRequest getReport = new GetReportsRequest()
      .setReportRequests(Arrays.asList(request));

Python

  response = self.analyticsreporting.reports().batchGet(
  body={
    "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "segmentId": "gaid::-3"
    }]
  }]
}).execute()

PHP

  // Create the Segments object for returning users.
  $segment = new Google_Service_AnalyticsReporting_Segment();
  $segment->setSegmentId("gaid::-3");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId("XXXX");
  $request->setDateRanges(array($dateRange));
  $request->setDimensions(array($browser, $segmentDimensions));
  $request->setSegments(array($segment));
  $request->setMetrics(array($sessions));

  // Create the GetReportsRequest object.
  $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $getReport->setReportRequests(array($request));

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  $response = $analyticsreporting->reports->batchGet( $body );

자바스크립트

gapi.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "segmentId": "gaid::-3"
    }]
  }]
}).execute(handleReportingResults)

C#

// Create the Segments object for returning users.
Segment segment = new Segment() { SegmentId = "gaid::-3" };

// Create the DateRange object.
DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

// Create the Metrics object.
Metric sessions = new Metric() { Expression = "ga:sessions", Alias = "sessions" };

//Create the browser dimension.
Dimension browser = new Dimension() { Name = "ga:browser" };

// Create the segment dimension.
Dimension segmentDimensions = new Dimension() { Name = "ga:segment" };

// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
{
    ViewId = "XXXX",
    DateRanges = new List<DateRange> { dateRange },
    Dimensions = new List<Dimension> { browser, segmentDimensions },
    Segments = new List<Segment> { segment },
    Metrics = new List<Metric> { sessions }
};

// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

// Call the batchGet method.
GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dimensions":[
    {
      "name": "ga:segment"
    },
    {
      "name":"ga:browser"
    }],
    "dateRanges":[
    {
      "startDate":"2015-06-15",
      "endDate":"2015-06-30"
    }],
    "metrics":[
    {
      "expression":"ga:sessions",
      "alias":"sessions"
    }],
    "segments":[
    {
      "segmentId": "gaid::-3"
    }]
  }]
}

설명 및 세그먼트 ID와 함께 사용 가능한 세그먼트 목록은 애널리틱스 관리 API v3의 목록 메서드를 사용하여 가져올 수 있습니다.

여러 세그먼트

Reporting API v4는 ReportRequest 정의 내에서 여러 세그먼트도 지원합니다. 다음은 여러 세그먼트를 포함하는 간단한 쿼리입니다.

자바

private static Segment buildSimpleSegment(
    String segmentName, String dimension, String dimensionFilterExpression) {
  // Create Dimension Filter.
  SegmentDimensionFilter dimensionFilter =
      new SegmentDimensionFilter()
          .setDimensionName(dimension)
          .setOperator("EXACT")
          .setExpressions(Arrays.asList(dimensionFilterExpression));

  // Create Segment Filter Clause.
  SegmentFilterClause segmentFilterClause =
      new SegmentFilterClause().setDimensionFilter(dimensionFilter);

  // Create the Or Filters for Segment.
  OrFiltersForSegment orFiltersForSegment =
      new OrFiltersForSegment().setSegmentFilterClauses(Arrays.asList(segmentFilterClause));

  // Create the Simple Segment.
  SimpleSegment simpleSegment =
      new SimpleSegment().setOrFiltersForSegment(Arrays.asList(orFiltersForSegment));

  // Create the Segment Filters.
  SegmentFilter segmentFilter = new SegmentFilter().setSimpleSegment(simpleSegment);

  // Create the Segment Definition.
  SegmentDefinition segmentDefinition =
      new SegmentDefinition().setSegmentFilters(Arrays.asList(segmentFilter));

  // Create the Dynamic Segment.
  DynamicSegment dynamicSegment =
      new DynamicSegment().setSessionSegment(segmentDefinition).setName(segmentName);

  // Create the Segments object.
  Segment segment = new Segment().setDynamicSegment(dynamicSegment);
  return segment;
}

private static void multipleSegmentsRequest(Analyticsreporting analyticsreporting) throws IOException {
  // Create the DateRange object.
  DateRange dateRange = new DateRange();
  dateRange.setStartDate("2015-06-15");
  dateRange.setEndDate("2015-06-30");

  // Create the Metrics object.
  Metric sessions = new Metric().setExpression("ga:sessions").setAlias("sessions");

  Dimension browser = new Dimension().setName("ga:browser");

  Dimension segmentDimensions = new Dimension().setName("ga:segment");

  Segment browserSegment =
      buildSimpleSegment("Sessions with Safari browser", "ga:browser", "Safari");

  Segment countrySegment =
      buildSimpleSegment("Sessions from United States", "ga:country", "United States");

  // Create the ReportRequest object.
  ReportRequest request =
      new ReportRequest()
          .setViewId("XXXX")
          .setDateRanges(Arrays.asList(dateRange))
          .setDimensions(Arrays.asList(browser, segmentDimensions))
          .setSegments(Arrays.asList(browserSegment, countrySegment))
          .setMetrics(Arrays.asList(sessions));

  // Create the GetReportsRequest object.
  GetReportsRequest getReport = new GetReportsRequest().setReportRequests(Arrays.asList(request));

  // Call the batchGet method.
  GetReportsResponse response = analyticsreporting.reports().batchGet(getReport).execute();

  printResults(response.getReports());
}

Python

response = self.analyticsreporting.reports().batchGet(
    body={
    "reportRequests":[
    {
      "viewId":"XXXX",
      "dateRanges":[
      {
        "endDate":"2015-06-30",
        "startDate":"2015-06-15"
      }],
      "dimensions":[
      {
        "name":"ga:browser"
      },
      {
        "name":"ga:segment"
      }],
      "metrics":[
      {
        "alias":"sessions",
        "expression":"ga:sessions"
      }],
      "segments":[
      {
        "dynamicSegment":
        {
          "name":"Safari",
          "sessionSegment":
          {
            "segmentFilters":[
            {
              "simpleSegment":
              {
                "orFiltersForSegment":[
                {
                  "segmentFilterClauses":[
                  {
                    "dimensionFilter":
                    {
                      "dimensionName":"ga:browser",
                      "expressions":["Safari"],
                      "operator":"EXACT"
                    }
                  }]
                }]
              }
            }]
          }
        }
      },
      {
        "dynamicSegment":
        {
          "name":"United States",
          "sessionSegment":
          {
            "segmentFilters":[
            {
              "simpleSegment":
              {
                "orFiltersForSegment":[
                {
                  "segmentFilterClauses":[
                  {
                    "dimensionFilter":
                    {
                      "dimensionName":"ga:country",
                      "expressions":["United States"],
                      "operator":"EXACT"
                    }
                  }]
                }]
              }
            }]
          }
        }
      }]
    }]
}).execute()

PHP

function  buildSimpleSegment($segmentName, $dimension, $dimensionFilterExpression) {
  // Create the segment dimension.
  $segmentDimensions = new Google_Service_AnalyticsReporting_Dimension();
  $segmentDimensions->setName("ga:segment");

  // Create Dimension Filter.
  $dimensionFilter = new Google_Service_AnalyticsReporting_SegmentDimensionFilter();
  $dimensionFilter->setDimensionName($dimension);
  $dimensionFilter->setOperator("EXACT");
  $dimensionFilter->setExpressions(array($dimensionFilterExpression));

  // Create Segment Filter Clause.
  $segmentFilterClause = new Google_Service_AnalyticsReporting_SegmentFilterClause();
  $segmentFilterClause->setDimensionFilter($dimensionFilter);

  // Create the Or Filters for Segment.
  $orFiltersForSegment = new Google_Service_AnalyticsReporting_OrFiltersForSegment();
  $orFiltersForSegment->setSegmentFilterClauses(array($segmentFilterClause));

  // Create the Simple Segment.
  $simpleSegment = new Google_Service_AnalyticsReporting_SimpleSegment();
  $simpleSegment->setOrFiltersForSegment(array($orFiltersForSegment));

  // Create the Segment Filters.
  $segmentFilter = new Google_Service_AnalyticsReporting_SegmentFilter();
  $segmentFilter->setSimpleSegment($simpleSegment);

  // Create the Segment Definition.
  $segmentDefinition = new Google_Service_AnalyticsReporting_SegmentDefinition();
  $segmentDefinition->setSegmentFilters(array($segmentFilter));

  // Create the Dynamic Segment.
  $dynamicSegment = new Google_Service_AnalyticsReporting_DynamicSegment();
  $dynamicSegment->setSessionSegment($segmentDefinition);
  $dynamicSegment->setName($segmentName);

  // Create the Segments object.
  $segment = new Google_Service_AnalyticsReporting_Segment();
  $segment->setDynamicSegment($dynamicSegment);
  return $segment;
}

function multipleSegmentsRequest(&$analyticsreporting) {

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("2015-06-15");
  $dateRange->setEndDate("2015-06-30");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  //Create the browser dimension.
  $browser = new Google_Service_AnalyticsReporting_Dimension();
  $browser->setName("ga:browser");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId("XXXX");
  $request->setDateRanges(array($dateRange));
  $request->setDimensions(array($browser, $segmentDimensions));
  $request->setMetrics(array($sessions));

  // Specifying multiple segments
  $browserSegment = buildSimpleSegment("Sessions with Safari browser", "ga:browser", "Safari");
  $countrySegment = buildSimpleSegment("Sessions from United States", "ga:country", "United States");
  $request->setSegments(array($browserSegment, $countrySegment));

  // Create the GetReportsRequest object.
  $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $getReport->setReportRequests(array($request));

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  $response = $analyticsreporting->reports->batchGet( $body );

  printResults($response->getReports());
}

자바스크립트

 gapi.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:segment"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name":"Safari",
        "sessionSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":[
              {
                "segmentFilterClauses":[
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "expressions":["Safari"],
                    "operator":"EXACT"
                  }
                }]
              }]
            }
          }]
        }
      }
    },
    {
      "dynamicSegment":
      {
        "name":"United States",
        "sessionSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":[
              {
                "segmentFilterClauses":[
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:country",
                    "expressions":["United States"],
                    "operator":"EXACT"
                  }
                }]
              }]
            }
          }]
        }
      }
    }]
  }]
 }).execute(handleReportingResults)

C#

public static Segment buildSimpleSegment(String segmentName, String dimension, String dimensionFilterExpression)
{
    // Create Dimension Filter.
    SegmentDimensionFilter dimensionFilter = new SegmentDimensionFilter() { DimensionName = dimension, Operator__ = "EXACT", Expressions = new List<string> { dimensionFilterExpression } };

    // Create Segment Filter Clause.
    SegmentFilterClause segmentFilterClause = new SegmentFilterClause() { DimensionFilter = dimensionFilter };

    // Create the Or Filters for Segment.
    OrFiltersForSegment orFiltersForSegment = new OrFiltersForSegment() { SegmentFilterClauses = new List<SegmentFilterClause> { segmentFilterClause } };

    // Create the Simple Segment.
    SimpleSegment simpleSegment = new SimpleSegment() { OrFiltersForSegment = new List<OrFiltersForSegment> { orFiltersForSegment } };

    // Create the Segment Filters.
    SegmentFilter segmentFilter = new SegmentFilter() { SimpleSegment = simpleSegment };

    // Create the Segment Definition.
    SegmentDefinition segmentDefinition = new SegmentDefinition() { SegmentFilters = new List<SegmentFilter> { segmentFilter } };

    // Create the Dynamic Segment.
    DynamicSegment dynamicSegment = new DynamicSegment() { SessionSegment = segmentDefinition, Name = segmentName };

    // Create the Segments object.
    Segment segment = new Segment() { DynamicSegment = dynamicSegment };

    return segment;
}

public static void multipleSegmentsRequest(AnalyticsReportingService analyticsreporting)
{
    if (analyticsreporting == null)
        throw new ArgumentException("Reporting service required");

    // Create the DateRange object.
    DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

    // Create the Metrics object.
    Metric sessions = new Metric() { Expression = "ga:sessions", Alias = "sessions" };

    Dimension browser = new Dimension() { Name = "ga:browser" };

    Dimension segmentDimensions = new Dimension() { Name = "ga:segment" };

    Segment browserSegment = buildSimpleSegment("Sessions with Safari browser", "ga:browser", "Safari");

    Segment countrySegment = buildSimpleSegment("Sessions from United States", "ga:country", "United States");

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest()
    {
        ViewId = "XXXX",
        DateRanges = new List<DateRange> { dateRange },
        Dimensions = new List<Dimension> { browser, segmentDimensions },
        Segments = new List<Segment> { browserSegment, countrySegment },
        Metrics = new List<Metric> { sessions }
    };

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

    // Call the batchGet method.
    GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

    printResults((List<Report>)response.Reports);
}

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:segment"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "segments":[
    {
      "dynamicSegment":
      {
        "name":"Safari",
        "sessionSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":[
              {
                "segmentFilterClauses":[
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:browser",
                    "expressions":["Safari"],
                    "operator":"EXACT"
                  }
                }]
              }]
            }
          }]
        }
      }
    },
    {
      "dynamicSegment":
      {
        "name":"United States",
        "sessionSegment":
        {
          "segmentFilters":[
          {
            "simpleSegment":
            {
              "orFiltersForSegment":[
              {
                "segmentFilterClauses":[
                {
                  "dimensionFilter":
                  {
                    "dimensionName":"ga:country",
                    "expressions":["United States"],
                    "operator":"EXACT"
                  }
                }]
              }]
            }
          }]
        }
      }
    }]
  }]
}

피봇

Reporting API v4에서는 피봇을 지원합니다. 피봇이 있는 요청은 두 번째 측정기준에서 데이터를 피봇하여 표의 정보를 재정렬합니다. 피봇에 대한 자세한 내용은 API 참조를 확인하세요.

자바

private static void pivotRequest(Analyticsreporting analyticsreporting) throws IOException {

    // Create the DateRange object.
    DateRange dateRange = new DateRange();
    dateRange.setStartDate("2015-06-15");
    dateRange.setEndDate("2015-06-30");

    // Create the Metric objects.
    Metric sessions = new Metric()
        .setExpression("ga:sessions")
        .setAlias("sessions");
    Metric pageviews = new Metric()
        .setExpression("ga:pageviews")
        .setAlias("pageviews");

    // Create the Dimension objects.
    Dimension browser = new Dimension()
        .setName("ga:browser");
    Dimension campaign = new Dimension()
        .setName("ga:campaign");
    Dimension age = new Dimension()
        .setName("ga:userAgeBracket");

    // Create the Pivot object.
    Pivot pivot = new Pivot()
        .setDimensions(Arrays.asList(age))
        .setMaxGroupCount(3)
        .setStartGroup(0)
        .setMetrics(Arrays.asList(sessions, pageviews));

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest()
        .setViewId("XXXX")
        .setDateRanges(Arrays.asList(dateRange))
        .setDimensions(Arrays.asList(browser, campaign))
        .setPivots(Arrays.asList(pivot))
        .setMetrics(Arrays.asList(sessions));

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest()
        .setReportRequests(Arrays.asList(request));

    // Call the batchGet method.
    GetReportsResponse response = analyticsreporting.reports().batchGet(getReport)
        .execute();

    printResults(response.getReports());
}

Python

response = self.analyticsreporting.reports().batchGet(
  body:{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:campaign"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "pivots":[
    {
      "dimensions":[
      {
        "name":"ga:userAgeBracket"
      }],
      "startGroup":"0",
      "maxGroupCount":"3",
      "metrics":[
      {
        "alias":"sessions",
        "expression":"ga:sessions"
      },
      {
        "alias":"pageviews",
        "expression":"ga:pageviews"
      }]
    }]
  }]
}).execute()

PHP

function pivotRequest(&$analyticsreporting) {
  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("2015-06-15");
  $dateRange->setEndDate("2015-06-30");

  // Create the Metric objects.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  $pageviews = new Google_Service_AnalyticsReporting_Metric();
  $pageviews->setExpression("ga:pageviews");
  $pageviews->setAlias("pageviews");

  // Create the Dimension objects.
  $browser = new Google_Service_AnalyticsReporting_Dimension();
  $browser->setName("ga:browser");

  $campaign = new Google_Service_AnalyticsReporting_Dimension();
  $campaign->setName("ga:campaign");

  $age = new Google_Service_AnalyticsReporting_Dimension();
  $age->setName("ga:userAgeBracket");

  // Create the Pivot object.
  $pivot = new Google_Service_AnalyticsReporting_Pivot();
  $pivot->setDimensions(array($age));
  $pivot->setMaxGroupCount(3);
  $pivot->setStartGroup(0);
  $pivot->setMetrics(array($sessions, $pageviews));

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId("XXXX");
  $request->setDateRanges(array($dateRange));
  $request->setDimensions(array($browser, $campaign));
  $request->setPivots(array($pivot));
  $request->setMetrics(array($sessions));

  // Create the GetReportsRequest object.
  $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $getReport->setReportRequests(array($request));

  // Call the batchGet method.
  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array($request) );
  $response = $analyticsreporting->reports->batchGet( $body );

  printResults($response->getReports());
}

자바스크립트

gapi.client.analyticsreporting.reports.batchGet({
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:campaign"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "pivots":[
    {
      "dimensions":[
      {
        "name":"ga:userAgeBracket"
      }],
      "startGroup":"0",
      "maxGroupCount":"3",
      "metrics":[
      {
        "alias":"sessions",
        "expression":"ga:sessions"
      },
      {
        "alias":"pageviews",
        "expression":"ga:pageviews"
      }]
    }]
  }]
}).execute(handleReportingResults)

C#

public static void pivotRequest(AnalyticsReportingService analyticsreporting)
{
    if (analyticsreporting == null)
        throw new ArgumentException("Reporting service required");

    // Create the DateRange object.
    DateRange dateRange = new DateRange() { StartDate = "2015-06-15", EndDate = "2015-06-30" };

    // Create the Metric objects.
    Metric sessions = new Metric() { Expression = "ga:sessions", Alias = "sessions" };

    Metric pageviews = new Metric() { Expression = "ga:pageviews", Alias = "pageviews" };

    // Create the Dimension objects.
    Dimension browser = new Dimension() { Name = "ga:browser" };
    Dimension campaign = new Dimension() { Name = "ga:campaign" };
    Dimension age = new Dimension() { Name = "ga:userAgeBracket" };

    // Create the Pivot object.
    Pivot pivot = new Pivot() { Dimensions = new List<Dimension> { age }, MaxGroupCount = 3, StartGroup = 0, Metrics = new List<Metric> { sessions, pageviews } };

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest()
    {
        ViewId = "XXXX",
        DateRanges = new List<DateRange> { dateRange },
        Dimensions = new List<Dimension> { browser, campaign },
        Pivots = new List<Pivot> { pivot },
        Metrics = new List<Metric> { sessions }
    };

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

    // Call the batchGet method.
    GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

    printResults((List<Report>)response.Reports);
}

JSON

{
  "reportRequests":[
  {
    "viewId":"XXXX",
    "dateRanges":[
    {
      "endDate":"2015-06-30",
      "startDate":"2015-06-15"
    }],
    "dimensions":[
    {
      "name":"ga:browser"
    },
    {
      "name":"ga:campaign"
    }],
    "metrics":[
    {
      "alias":"sessions",
      "expression":"ga:sessions"
    }],
    "pivots":[
    {
      "dimensions":[
      {
        "name":"ga:userAgeBracket"
      }],
      "startGroup":"0",
      "maxGroupCount":"3",
      "metrics":[
      {
        "alias":"sessions",
        "expression":"ga:sessions"
      },
      {
        "alias":"pageviews",
        "expression":"ga:pageviews"
      }]
    }]
  }]
}

동질 집단

동질 집단은 공통 API를 공유하는 사용자 그룹에 대한 보고서를 생성할 수 있는 Reporting API v4의 새로운 기능입니다. 동질 집단에 대한 자세한 내용은 개발 가이드API 참조를 확인하세요.

자바

private static void cohortRequest(Analyticsreporting analyticsreporting) throws IOException {
  // Create the ReportRequest object.
  ReportRequest request = new ReportRequest().setViewId("XXXX");

  // Set the cohort dimensions
  request.setDimensions(Arrays.asList(
      new Dimension().setName("ga:cohort"), new Dimension().setName("ga:cohortNthWeek")));
  // Set the cohort metrics
  request.setMetrics(Arrays.asList(
      new Metric().setExpression("ga:cohortTotalUsersWithLifetimeCriteria"),
      new Metric().setExpression("ga:cohortRevenuePerUser")));

  // Create the first cohort
  Cohort cohort1 =
      new Cohort()
          .setName("cohort_1")
          .setType("FIRST_VISIT_DATE")
          .setDateRange(new DateRange().setStartDate("2015-08-01").setEndDate("2015-09-01"));

  // Create the second cohort which only differs from the first one by the date range
  Cohort cohort2 =
      new Cohort()
          .setName("cohort21")
          .setType("FIRST_VISIT_DATE")
          .setDateRange(new DateRange().setStartDate("2015-07-01").setEndDate("2015-08-01"));

  // Create the cohort group
  CohortGroup cohortGroup = new CohortGroup();
  cohortGroup.setCohorts(Arrays.asList(cohort1, cohort2));
  cohortGroup.setLifetimeValue(true);

  request.setCohortGroup(cohortGroup);

  // Create the GetReportsRequest object.
  GetReportsRequest getReport = new GetReportsRequest().setReportRequests(Arrays.asList(request));

  // Call the batchGet method.
  GetReportsResponse response = analyticsreporting.reports().batchGet(getReport).execute();

  printResults(response.getReports());
}

PHP

function cohortRequest(&$analyticsreporting) {
    // Create the ReportRequest object.
    $request = new Google_Service_AnalyticsReporting_ReportRequest();
    $request->setViewId("XXXX");

    $cohortDimension = new Google_Service_AnalyticsReporting_Dimension();
    $cohortDimension->setName("ga:cohort");

    $cohortNthWeekDimension = new Google_Service_AnalyticsReporting_Dimension();
    $cohortNthWeekDimension->setName("ga:cohortNthWeek");

    // Set the cohort dimensions
    $request->setDimensions(array($cohortDimension, $cohortNthWeekDimension));

    $cohortTotalUsersMetric = new Google_Service_AnalyticsReporting_Metric();
    $cohortTotalUsersMetric->setExpression("ga:cohortTotalUsersWithLifetimeCriteria");

    $cohortRevenuePerUserMetric = new Google_Service_AnalyticsReporting_Metric();
    $cohortRevenuePerUserMetric->setExpression("ga:cohortRevenuePerUser");

    // Set the cohort metrics
    $request->setMetrics(array($cohortTotalUsersMetric, $cohortRevenuePerUserMetric));

    $dateRange1 = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange1->setStartDate("2015-08-01");
    $dateRange1->setEndDate("2015-09-01");

    // Create the first cohort
    $cohort1 = new Google_Service_AnalyticsReporting_Cohort();
    $cohort1->setName("cohort_1");
    $cohort1->setType("FIRST_VISIT_DATE");
    $cohort1->setDateRange($dateRange1);

    $dateRange2 = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange2->setStartDate("2015-07-01");
    $dateRange2->setEndDate("2015-08-01");

    // Create the second cohort which only differs from the first one by the date range
    $cohort2 = new Google_Service_AnalyticsReporting_Cohort();
    $cohort2->setName("cohort_2");
    $cohort2->setType("FIRST_VISIT_DATE");
    $cohort2->setDateRange($dateRange2);

    // Create the cohort group
    $cohortGroup = new Google_Service_AnalyticsReporting_CohortGroup();
    $cohortGroup->setCohorts(array($cohort1, $cohort2));
    $cohortGroup->setLifetimeValue(true);

    $request->setCohortGroup($cohortGroup);

    // Create the GetReportsRequest object.
    $getReport = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $getReport->setReportRequests(array($request));

    // Call the batchGet method.
    $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $body->setReportRequests( array($request) );
    $response = $analyticsreporting->reports->batchGet( $body );

    printResults($response->getReports());
}

Python

response = self.analyticsreporting.reports().batchGet(body={
    "reportRequests": [
        {
            "viewId": "XXXX",
            "dimensions": [
                {"name": "ga:cohort"},
                {"name": "ga:cohortNthWeek"}],
            "metrics": [
                {"expression": "ga:cohortTotalUsersWithLifetimeCriteria"},
                {"expression": "ga:cohortRevenuePerUser"}
            ],
            "cohortGroup": {
                "cohorts": [{
                    "name": "cohort 1",
                    "type": "FIRST_VISIT_DATE",
                    "dateRange": {
                        "startDate": "2015-08-01",
                        "endDate": "2015-09-01"
                    }
                },
                            {
                                "name": "cohort 2",
                                "type": "FIRST_VISIT_DATE",
                                "dateRange": {
                                    "startDate": "2015-07-01",
                                    "end_date": "2015-08-01"
                                }
                            }],
                "lifetimeValue": True
            }
        }]
}).execute()

C#

private static void cohortRequest(AnalyticsReportingService analyticsreporting)
{
    if (analyticsreporting == null)
        throw new ArgumentException("Reporting service required");

    // Create the ReportRequest object.
    ReportRequest request = new ReportRequest() { ViewId = "XXXX" };

    // Set the cohort dimensions
    request.Dimensions  = new List<Dimension> { new Dimension() { Name = "ga:cohort" }, new Dimension() { Name = "ga:cohortNthWeek" } } ;

    // Set the cohort metrics
    request.Metrics = new List<Metric> { new Metric() { Expression = "ga:cohortTotalUsersWithLifetimeCriteria" }, new Metric() { Expression = "ga:cohortRevenuePerUser" } };

    // Create the first cohort
    Cohort cohort1 =  new Cohort() { Name = "cohort_1", Type = "FIRST_VISIT_DATE", DateRange = new DateRange() { StartDate = "2015-08-01", EndDate = "2015-09-01" } };

    // Create the second cohort which only differs from the first one by the date range
    Cohort cohort2 = new Cohort() { Name = "cohort21", Type = "FIRST_VISIT_DATE", DateRange = new DateRange() { StartDate = "2015-07-01", EndDate = "2015-08-01" } };

    // Create the cohort group
    CohortGroup cohortGroup = new CohortGroup();
    cohortGroup.Cohorts = new List<Cohort> { cohort1, cohort2 };
    cohortGroup.LifetimeValue = true;
    request.CohortGroup = cohortGroup;

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = new List<ReportRequest> { request } };

    // Call the batchGet method.
    GetReportsResponse response = analyticsreporting.Reports.BatchGet(getReport).Execute();

    printResults((List<Report>)response.Reports);
}

JSON

{
  "reportRequests": [
    {
        "viewId": "XXXX",
        "dimensions": [
            {"name": "ga:cohort" },
            {"name": "ga:cohortNthWeek" }],
        "metrics": [
            {"expression": "ga:cohortTotalUsersWithLifetimeCriteria"},
            {"expression": "ga:cohortRevenuePerUser"}
        ],
        "cohortGroup": {
            "cohorts": [{
                "name": "cohort 1",
                "type": "FIRST_VISIT_DATE",
                "dateRange": {
                    "startDate": "2015-08-01",
                    "endDate": "2015-09-01"
                }
            },
            {
                "name": "cohort 2",
                "type": "FIRST_VISIT_DATE",
                "dateRange": {
                    "startDate": "2015-07-01",
                    "end_date": "2015-08-01"
                }
            }],
           "lifetimeValue": True
        }
    }]
}