概览

您可以使用 Google Analytics Data API v1 生成数据透视表。数据透视 表格是一种数据摘要工具,通过重新排列表格 透视(轮播)一个或多个数据,以增加表格中的信息 维度。

以下面的原始数据表为例:

原始数据表

使用此数据可以构建数据透视表,将 按浏览器细分的会话数据,其中国家/地区和语言维度选为 其他数据透视

透视数据表

核心报告的共同功能

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

数据透视报告方法

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

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

  • batchRunPivotReports 此 是 runPivotReport 方法的批处理版本,支持生成 生成多份报告。

选择举报实体

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

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

生成的报告将根据 Google Analytics 事件数据生成 特定 Google Analytics 媒体资源中收集的信息。

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

数据透视报表请求

要构建包含数据透视表的请求,请使用 runPivotReportbatchRunPivotReports 方法。

要请求透视数据,您可以构建一个 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 对象 body 来定义报告数据透视。每个 Pivot 都描述了可见维度 列和行。

只要达到限制的乘积,Data API v1 就支持多个数据透视 参数不能超过 100,000。

以下代码段演示了如何使用 pivots 构建 按国家/地区统计的会话数,按browser维度透视数据。请注意 查询使用 orderBys 字段 排序限制offset 字段来实现分页

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

维度

维度用于描述以下各项的事件数据并对其进行分组 网站或应用例如,city 维度表示城市(“巴黎”) 或“纽约”)。在报告请求中,您可以 指定零个或多个维度。

必须在 维度 字段。这些维度必须同时显示在报告中 fieldNamesPivot 对象的特定字段。 如果某个维度未在任何 数据透视查询的数据。并非每个维度都必须存在于数据透视的 fieldNames。维度只能用在过滤器中,不能用在 任意数据透视的 fieldNames

以下代码段演示了 dimensionfieldNames 字段的用法 对于包含 browsercountrylanguage 数据透视的表:

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

指标汇总

使用 metricAggregations Pivot 对象的字段,用于计算聚合指标 每个数据透视的值。

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

以下是一个查询代码段,该查询请求 browser 个数据透视维度:

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

计算指标会以汇总的形式返回 RunPivotReportResponse 的 对象。对于汇总指标行,dimensionValues 字段 包含特殊值 RESERVED_TOTALRESERVED_MAXRESERVED_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"
        }
      ]
    },
  ....

  }

分页

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

Data API v1 支持多个数据透视,前提是 limit 的产品 参数不能超过 100,000。

以下代码段演示了如何将 offsetlimit 字段用于 以 10 的偏移量检索接下来的五个 language 维度:

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

过滤

核心报告功能类似, 请求级范围的维度过滤条件 如果需要在数据透视报表中进行维度过滤,则必须使用 请求。

排序

可以针对每个数据透视控制数据透视报表查询的排序行为 orderBys Pivot 对象的字段,该对象包含 OrderBy 对象。

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

此示例展示了用于透视报告的数据透视定义的代码段 “browser”维度,按 sessions 指标对结果进行排序 按降序排列。

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

举报响应

数据透视的数据透视表报表响应 Report API 请求主要是标头和行。

响应标头

数据透视表报表标头由 PivotHeadersDimensionHeadersMetricHeaders,用于列出 数据透视报表。

例如,包含 browsercountrylanguage 数据透视维度的报告 而 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 方法与核心报告方法的响应不同 例如 runReportbatchRunReports 在该示例中,每个数据透视表报表响应行都代表 表格,而在常规报告中,一个响应行代表完整的 表格行。

以下是针对 包含 browsercountrylanguage 数据透视维度以及 sessions 指标。系统会分别返回数据透视报告的每个单元格:

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

  ]

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

原始数据表

客户端库

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

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

PHP

<ph type="x-smartling-placeholder"></ph> google-analytics-data/src/run_pivot_report.php
<ph type="x-smartling-placeholder"></ph> 在 Cloud Shell 中打开 在 GitHub 上查看
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

<ph type="x-smartling-placeholder"></ph> google-analytics-data/run_pivot_report.py
<ph type="x-smartling-placeholder"></ph> 在 Cloud Shell 中打开 在 GitHub 上查看
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

<ph type="x-smartling-placeholder"></ph> google-analytics-data/run_pivot_report.js
<ph type="x-smartling-placeholder"></ph> 在 Cloud Shell 中打开 在 GitHub 上查看

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

演示应用

请参阅 Google Analytics API v1 透视报告演示 应用 ,通过示例了解如何使用 JavaScript 构建和显示数据透视表。