Примеры

Оптимизируйте свои подборки Сохраняйте и классифицируйте контент в соответствии со своими настройками.

В этой статье приведены примеры использования различных функций Google Analytics Reporting API версии 4.

Параметры и показатели

Ниже можно ознакомиться с простым примером, в котором представлено всего несколько параметров и показателей. С их полным перечнем можно ознакомиться здесь. Параметры и показатели – это настраиваемые повторные объекты, которые передаются в коде.

Java

// 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 );

JavaScript

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"
      }]
    }]
}

Несколько диапазонов дат

Ниже приведен пример с несколькими диапазонами дат.

Java

// 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));

JavaScript

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.

Java

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");
        }
      }
    }
  }
}

JavaScript

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"
                ]
              }
            ]
          },
        ],
        ...
      }
    }
  ]
}

Выражения на базе показателей

Повторяющиеся параметры metrics могут принимать значения любого показателя. Также можно создавать собственные показатели, комбинируя доступные показатели с помощью математических выражений. Поскольку в примере ниже представлена операция деления, параметру formattingType необходимо присвоить значение FLOAT, а также использовать параметр alias.

Java

// 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");

JavaScript

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 версии 4 можно самостоятельно определять столбцы гистограмм и порядок их сортировки, что избавляет от необходимости обрабатывать данные на стороне клиента. Ниже приведен пример кода для сегментации. Обратите внимание, что он содержит параметр orderBy. Этот параметр нужен, чтобы правильно упорядочить сегменты.

Java

// 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");

JavaScript

 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. Определить сегмент можно динамически в коде запроса или указав идентификатор существующего сегмента. Ниже приведен пример первого способа.

Java

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());
}

JavaScript

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 параметра Segment. В примере ниже показано, как создать отдельный сегмент для вернувшихся пользователей.

Java

  // 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 );

JavaScript

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"
    }]
  }]
}

Полный список доступных сегментов с описаниями и идентификаторами можно получить в Analytics Management API версии 3 с помощью метода list.

Несколько сегментов

Reporting API версии 4 поддерживает использование нескольких сегментов в параметре ReportRequest. Ниже приведен пример простого запроса с несколькими сегментами.

Java

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());
}

JavaScript

 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 версии 4 поддерживается создание сводных таблиц, данные в которых можно упорядочивать по двум параметрам. Подробнее…

Java

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());
}

JavaScript

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"
      }]
    }]
  }]
}

Когорты

Когорты – новая функция Reporting API версии 4, позволяющая создавать отчеты по группам пользователей с одной общей характеристикой. Подробнее о ней можно узнать в руководстве для разработчиков и справке по API.

Java

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
        }
    }]
}