概览

借助 Google Analytics Data API v1,您可以生成数据透视表。数据透视表是一种数据汇总工具,通过在一个或多个维度上透视(旋转)数据来重新排列数据表中的信息,从而实现数据可视化。

例如,假设有以下原始数据表:

原始数据表

使用这些数据可以构建数据透视表,按浏览器细分会话数据,并选择国家/地区和语言维度作为其他透视。

透视数据表

与核心报告共用的功能

对于许多共享功能,透视报告请求与核心报告请求具有相同的语义。例如,分页、维度过滤条件和用户属性在数据透视报告中的行为与在核心报告中相同。本指南重点介绍数据透视报告功能。如需熟悉 Data API v1 的核心报告功能,请参阅报告基础知识指南以及高级用例指南。

透视报告方法

Data API v1 在以下报告方法中支持透视功能:

  • runPivotReport:此方法会返回您的 Google Analytics 事件数据的自定义数据透视报告。每个数据透视表都描述了报告响应中可见的维度列和行。

  • batchRunPivotReports:这是 runPivotReport 方法的批量版本,可让您通过一次 API 调用生成多个报告。

选择报告实体

Data API v1 的所有方法都要求在网址请求路径中以 properties/GA_PROPERTY_ID 的形式指定 Google Analytics 媒体资源标识符,例如:

  POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runPivotReport

系统会根据在指定 Google Analytics 媒体资源中收集的 Google Analytics 事件数据生成报告。

如果您使用的是 Data API 客户端库,则无需手动操作请求网址路径。大多数 API 客户端都会提供一个 property 参数,该参数需要 properties/GA_PROPERTY_ID 形式的字符串。如需查看有关如何使用客户端库的示例,请参阅快速入门指南。

透视报告请求

如需构建包含数据透视表的请求,请使用 runPivotReport 或 batchRunPivotReports 方法。

如需请求透视数据,您可以构建 RunPivotReportRequest 对象。我们建议您从以下请求参数开始:

  • dateRanges 字段中的有效条目。
  • dimensions 字段中至少有一个有效条目。
  • metrics 字段中至少有一个有效条目。
  • pivots 字段中至少有两个有效的透视条目。

以下是包含推荐字段的请求示例:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runPivotReport
  {
    "dateRanges": [{ "startDate": "2020-09-01", "endDate": "2020-09-15" }],
    "dimensions": [
        { "name": "browser" },
        { "name": "country" },
        { "name": "language" }
      ],
    "metrics": [{ "name": "sessions" }],
    "pivots": [
      {
        "fieldNames": [
          "browser"
        ],
        "limit": 5
      },
      {
        "fieldNames": [
          "country"
        ],
        "limit": 250
      },
      {
        "fieldNames": [
          "language"
        ],
        "limit": 15
      }
    ]
  }

数据透视

使用请求正文的 pivot 字段中的 Pivot 对象来定义报告透视。每个 Pivot 描述报告响应中可见的维度列和行。

Data API v1 支持多个透视,只要每个透视的 limit 参数的乘积不超过 100,000 即可。

以下代码段演示了如何使用 pivots 构建按国家/地区统计会话数的报告,并按 browser 维度进行透视。请注意,该查询如何使用 orderBys 字段进行排序,以及如何使用 limit 和 offset 字段实现分页。

    "pivots": [
      {
        "fieldNames": [
          "country"
        ],
        "limit": 250,
        "orderBys": [
          {
            "dimension": {
              "dimensionName": "country"
            }
          }
        ]
      },
      {
        "fieldNames": [
          "browser"
        ],
        "offset": 3,
        "limit": 3,
        "orderBys": [
          {
            "metric": {
              "metricName": "sessions"
            },
            "desc": true
          }
        ]
      }
    ],
    ...

维度

维度用于描述和分组网站或应用的事件数据。例如,city 维度表示每个事件源自哪个城市(“巴黎”或“纽约”)。在报告请求中,您可以指定零个或多个维度。

维度必须在请求正文的 dimensions 字段中定义。如需在报告中显示,这些维度还必须列在 Pivot 对象的 fieldNames 字段中。如果某个维度未在透视查询的任何透视中使用,则该维度不会显示在报告中。并非每个维度都必须存在于数据透视表的 fieldNames 中。维度只能在过滤条件中使用,而不能在任何数据透视表的 fieldNames 中使用。

以下代码段演示了如何对具有 browser、country 和 language 透视的表使用 dimension 和 fieldNames 字段:

    "pivots": [
      {
        "fieldNames": [
          "browser"
        ],
        "limit": 5,
        "orderBys": [
          {
            "metric": {
              "metricName": "sessions"
            },
            "desc": true
          }
        ]
      },
      {
        "fieldNames": [
          "country"
        ],
        "limit": 250,
        "orderBys": [
          {
            "dimension": {
              "dimensionName": "country"
            }
          }
        ]
      },
      {
        "fieldNames": [
          "language"
        ],
        "limit": 10
      }
    ],

指标

指标是对网站或应用事件数据的定量衡量。在报告请求中,您可以指定一个或多个指标。如需查看可在请求中指定的 API 指标名称的完整列表,请参阅 API 指标。

在透视报告请求中,指标是使用请求正文的 metrics 字段定义的,这与核心报告方法类似。

以下示例指定了要在报告中用作指标值的会话数:

    "metrics": [
      {
        "name": "sessions"
      }
    ],

指标汇总

使用 Pivot 对象的 metricAggregations 字段计算每个透视的汇总指标值。

只有在请求中指定 metricAggregations 字段时,系统才会计算聚合值。

以下示例是一个查询代码段,用于请求 browser 数据透视维度的总计:

"pivots": [
  {
    "fieldNames": [
      "browser"
    ],
    "limit": 10,
    "metricAggregations": [
      "TOTAL",
    ]
  },
  ...

计算指标会在 RunPivotReportResponse 对象的 aggregates 字段中返回。对于汇总指标行,dimensionValues 字段包含特殊值 RESERVED_TOTAL、RESERVED_MAX 或 RESERVED_MIN。

  "aggregates": [
    {
      "dimensionValues": [
        {
          "value": "Chrome"
        },
        {
          "value": "RESERVED_TOTAL"
        },
        {
          "value": "RESERVED_TOTAL"
        }
      ],
      "metricValues": [
        {
          "value": "4"
        }
      ]
    },
    {
      "dimensionValues": [
        {
          "value": "Firefox"
        },
        {
          "value": "RESERVED_TOTAL"
        },
        {
          "value": "RESERVED_TOTAL"
        }
      ],
      "metricValues": [
        {
          "value": "6"
        }
      ]
    },
  ....

  }

分页

与核心报告方法类似,透视请求允许您在 Pivot 对象中指定 limit 和 offset 字段,以实现分页。分页设置会分别应用于每个数据透视。 每个 Pivot 对象都需要 limit 字段,以限制报告基数。

Data API v1 支持多个透视,只要每个透视的 limit 参数的乘积不超过 100,000 即可。

以下代码段演示了如何使用 offset 和 limit 字段检索接下来的五个 language 维度(偏移量为 10):

      {
        "fieldNames": [
          "language"
        ],
        "offset": 10,
        "limit": 5
      }

过滤

与核心报告功能类似,如果您想在透视报告请求中过滤维度,则必须使用请求范围的维度过滤条件。

排序

您可以使用 Pivot 对象的 orderBys 字段(其中包含 OrderBy 对象的列表)单独控制每个透视的透视报告查询的排序行为。

每个 OrderBy 都可以包含以下内容之一:

此示例显示了一个数据透视定义代码段,该代码段会根据 browser 维度对报告进行透视,并按 sessions 指标降序排列结果。

      {
        "fieldNames": [
          "browser"
        ],
        "limit": 5,
        "orderBys": [
          {
            "metric": {
              "metricName": "sessions"
            },
            "desc": true
          }
        ]
      }

举报回答

数据透视报告 API 请求的数据透视报告响应主要由标题和行组成。

响应标头

透视报告标题由 PivotHeaders、DimensionHeaders 和 MetricHeaders 组成,其中列出了透视报告中的列。

例如,如果报告包含 browser、country 和 language 透视维度以及 sessions 指标,则会生成如下所示的标题:

{
  "pivotHeaders": [
    {
      "pivotDimensionHeaders": [
        {
          "dimensionValues": [
            {
              "value": "Chrome"
            }
          ]
        },
        {
          "dimensionValues": [
            {
              "value": "Firefox"
            }
          ]
        },
        ...

      ],
      ...
    },
    {
      "pivotDimensionHeaders": [
        {
          "dimensionValues": [
            {
              "value": "United States"
            }
          ]
        },
        {
          "dimensionValues": [
            {
              "value": "Canada"
            }
          ]
        },
        ...

      ],
      ...
    },
    {
      "pivotDimensionHeaders": [
        {
          "dimensionValues": [
            {
              "value": "English"
            }
          ]
        },
        {
          "dimensionValues": [
            {
              "value": "French"
            }
          ]
        },
        ...

      ],
      ...
    }
  ],
  "dimensionHeaders": [
    {
      "name": "browser"
    },
    {
      "name": "country"
    },
    {
      "name": "language"
    }
  ],
  "metricHeaders": [
    {
      "name": "sessions",
      "type": "TYPE_INTEGER"
    }
  ],
  ...

}

下图说明了透视报告响应的每个组件在呈现透视报告时所起的作用:

原始数据表

响应行

runPivotReport 和 batchRunPivotReports 方法的透视报告响应与核心报告方法(如 runReport 和 batchRunReports)的响应不同,因为每个透视报告响应行都代表表格中的一个单元格,而在常规报告中,单个响应行代表一个完整的表格行。

以下示例展示了针对包含 browser、country 和 language 透视维度以及 sessions 指标的查询,透视报告响应的片段。透视报告的每个单元格都会单独返回:

  "rows": [
    {
      "dimensionValues": [
        {
          "value": "Chrome"
        },
        {
          "value": "United States"
        },
        {
          "value": "English"
        }
      ],
      "metricValues": [
        {
          "value": "1"
        }
      ]
    },
    {
      "dimensionValues": [
        {
          "value": "Firefox"
        },
        {
          "value": "Canada"
        },
        {
          "value": "French"
        }
      ],
      "metricValues": [
        {
          "value": "3"
        }
      ]
    },
    ...

  ]

此数据对应于下表中突出显示的两个单元格:

原始数据表

客户端库

如需了解如何安装和配置客户端库,请参阅快速入门指南。

以下示例使用客户端库运行透视查询,以按浏览器维度透视,构建按国家/地区统计的会话数报告。

PHP

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\OrderBy;
use Google\Analytics\Data\V1beta\OrderBy\DimensionOrderBy;
use Google\Analytics\Data\V1beta\OrderBy\MetricOrderBy;
use Google\Analytics\Data\V1beta\Pivot;
use Google\Analytics\Data\V1beta\RunPivotReportRequest;
use Google\Analytics\Data\V1beta\RunPivotReportResponse;

/**
 * Runs a pivot query to build a report of session counts by country,
 * pivoted by the browser dimension.
 * @param string $propertyId Your GA-4 Property ID
 */
function run_pivot_report(string $propertyId)
{
    // Create an instance of the Google Analytics Data API client library.
    $client = new BetaAnalyticsDataClient();

    // Make an API call.
    $request = (new RunPivotReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setDateRanges([new DateRange([
            'start_date' => '2021-01-01',
            'end_date' => '2021-01-30',
            ]),
        ])
        ->setPivots([
            new Pivot([
                'field_names' => ['country'],
                'limit' => 250,
                'order_bys' => [new OrderBy([
                    'dimension' => new DimensionOrderBy([
                        'dimension_name' => 'country',
                    ]),
                ])],
            ]),
            new Pivot([
                'field_names' => ['browser'],
                'offset' => 3,
                'limit' => 3,
                'order_bys' => [new OrderBy([
                    'metric' => new MetricOrderBy([
                        'metric_name' => 'sessions',
                    ]),
                    'desc' => true,
                ])],
            ]),
        ])
        ->setMetrics([new Metric(['name' => 'sessions'])])
        ->setDimensions([
            new Dimension(['name' => 'country']),
            new Dimension(['name' => 'browser']),
        ]);
    $response = $client->runPivotReport($request);

    printPivotReportResponse($response);
}

/**
 * Print results of a runPivotReport call.
 * @param RunPivotReportResponse $response
 */
function printPivotReportResponse(RunPivotReportResponse $response)
{
    print 'Report result: ' . PHP_EOL;

    foreach ($response->getRows() as $row) {
        printf(
            '%s %s' . PHP_EOL,
            $row->getDimensionValues()[0]->getValue(),
            $row->getMetricValues()[0]->getValue()
        );
    }
}

Python

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    DateRange,
    Dimension,
    Metric,
    OrderBy,
    Pivot,
    RunPivotReportRequest,
)


def run_sample():
    """Runs the sample."""
    # TODO(developer): Replace this variable with your Google Analytics 4
    #  property ID before running the sample.
    property_id = "YOUR-GA4-PROPERTY-ID"
    run_pivot_report(property_id)


def run_pivot_report(property_id="YOUR-GA4-PROPERTY-ID"):
    """Runs a pivot query to build a report of session counts by country,
    pivoted by the browser dimension."""
    client = BetaAnalyticsDataClient()

    request = RunPivotReportRequest(
        property=f"properties/{property_id}",
        date_ranges=[DateRange(start_date="2021-01-01", end_date="2021-01-30")],
        pivots=[
            Pivot(
                field_names=["country"],
                limit=250,
                order_bys=[
                    OrderBy(
                        dimension=OrderBy.DimensionOrderBy(dimension_name="country")
                    )
                ],
            ),
            Pivot(
                field_names=["browser"],
                offset=3,
                limit=3,
                order_bys=[
                    OrderBy(
                        metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True
                    )
                ],
            ),
        ],
        metrics=[Metric(name="sessions")],
        dimensions=[Dimension(name="country"), Dimension(name="browser")],
    )
    response = client.run_pivot_report(request)
    print_run_pivot_report_response(response)


def print_run_pivot_report_response(response):
    """Prints results of a runPivotReport call."""
    print("Report result:")
    for row in response.rows:
        for dimension_value in row.dimension_values:
            print(dimension_value.value)

        for metric_value in row.metric_values:
            print(metric_value.value)

Node.js

  // TODO(developer): Uncomment this variable and replace with your
  // Google Analytics 4 property ID before running the sample.
  // propertyId = 'YOUR-GA4-PROPERTY-ID';

  // Imports the Google Analytics Data API client library.
  const {BetaAnalyticsDataClient} = require('@google-analytics/data');

  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests.
  const analyticsDataClient = new BetaAnalyticsDataClient();

  // Runs a pivot query to build a report of session counts by country, pivoted
  // by the browser dimension.
  async function runPivotReport() {
    const [response] = await analyticsDataClient.runPivotReport({
      property: `properties/${propertyId}`,
      dateRanges: [
        {
          startDate: '2021-01-01',
          endDate: '2021-01-30',
        },
      ],
      pivots: [
        {
          fieldNames: ['country'],
          limit: 250,
          orderBys: [
            {
              dimension: {
                dimensionName: 'country',
              },
            },
          ],
        },
        {
          fieldNames: ['browser'],
          offset: 3,
          limit: 3,
          orderBys: [
            {
              metric: {
                metricName: 'sessions',
              },
              desc: true,
            },
          ],
        },
      ],
      metrics: [
        {
          name: 'sessions',
        },
      ],
      dimensions: [
        {
          name: 'country',
        },
        {
          name: 'browser',
        },
      ],
    });
    printPivotReportResponse(response);
  }

  runPivotReport();

  // Prints results of a runReport call.
  function printPivotReportResponse(response) {
    console.log('Report result:');
    response.rows.forEach((row) => {
      row.dimensionValues.forEach((dimensionValue) => {
        console.log(dimensionValue.value);
      });

      row.metricValues.forEach((metricValue) => {
        console.log(metricValue.value);
      });
    });
  }

演示应用

如需查看如何使用 JavaScript 构建和显示透视报告的示例,请参阅 Google Analytics API v1 透视报告演示应用。