サンプル

コレクションでコンテンツを整理 必要に応じて、コンテンツの保存と分類を行います。

この記事では、Google アナリティクス Reporting API v4 の機能のサンプルを紹介します。

ディメンションと指標

以下に示すのは、ディメンションと指標が数個しか含まれないシンプルなリクエストです。使用可能なディメンションと指標について詳しくは、ディメンションと指標のリファレンスをご覧ください。ディメンションと指標は、POST 本文で渡される設定可能な反復オブジェクトです。

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

指標の式

反復される指標のパラメータには既存の指標のどれでも指定できますが、既存の指標を組み合わせて新しい指標の式を作り、計算に基づくカスタム指標を作成することもできます。以下のサンプルは除算演算であるため、formattingTypeFLOAT に設定する必要もあります。また、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 v4 では、一連のカスタム ヒストグラム バケットを独自に定義することもできるため、コストの高いデータ処理をクライアント側で実行する手間を省けます。バケット ディメンションの例を以下に示します。バケット ディメンションを正しい順序で並べ替える 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 を追加する必要があることにも注意してください。セグメント ディメンションをクエリ内で動的に作成することも、既存の組み込み / カスタム セグメントの ID を指定することもできます。動的セグメント定義の使用例を以下に示します。

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 フィールドを使用して、既定のセグメント ID を指定することも可能です。以下の例では、リピーターのセグメントが作成されます。

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

アナリティクス Management API v3 の list メソッドを使用して、使用可能なセグメントとその説明およびセグメント ID のリストを含めることができます。

複数のセグメント

Reporting API v4 では、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 v4 では、ピボットがサポートされます。ピボットを使用したリクエストでは、セカンダリ ディメンションでデータをピボットすることにより、テーブルに含まれる情報が再配置されます。ピボットについて詳しくは、API リファレンスをご覧ください。

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 v4 の新しい機能で、共通の特性を持つユーザーのグループについてのレポートを生成できます。コホートについて詳しくは、開発ガイド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
        }
    }]
}