Google Analytics (分析) Data API v1 可讓您產生資料透視表。資料透視表是一種資料摘要工具,可藉由在一或多個維度上重新調整 (旋轉) 資料,重新安排 (旋轉) 表格資訊,以視覺化方式呈現資料。
我們以下列原始資料表為例:
這些資料可用於建構資料透視表、依瀏覽器細分工作階段資料,並且選取國家/地區和語言維度做為其他資料透視依據。
與核心報表共用的功能
針對許多共用功能,樞紐分析報表要求與核心報表要求的語意相同。舉例來說,分頁、維度篩選器和使用者屬性在資料透視報表的運作方式與核心報表相同。本指南著重於資料透視報表功能。如要深入瞭解 Data API v1 的核心報表功能,請參閱報表基本指南和進階用途指南。
資料透視報表方法
Data API 第 1 版在下列報表方法中支援資料透視功能:
runPivotReport 這個方法會傳回 Google Analytics (分析) 事件資料的自訂資料透視報表。每個資料透視表都會說明報表回應中可見的維度欄和資料列。
batchRunPivotReports 是
runPivotReport
方法的批次版本,可使用單一 API 呼叫產生多份報表。
選取檢舉實體
所有 Data API v1 方法都需要在網址要求路徑內指定 Google Analytics (分析) 4 資源 ID,格式為 properties/GA4_PROPERTY_ID
,例如:
POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_PROPERTY_ID:runPivotReport
系統會根據指定 Google Analytics (分析) 4 資源中收集到的 Google Analytics (分析) 事件資料產生產生的報表。
如果您使用其中一個 Data API 用戶端程式庫,則不需要手動操控要求網址路徑。多數 API 用戶端提供的 property
參數會預期字串格式為 properties/GA4_PROPERTY_ID
。如需使用用戶端程式庫的範例,請參閱快速入門指南。
樞紐報告要求
如要透過資料透視表建構要求,請使用 runPivotReport 或 batchRunPivotReports 方法。
如要要求已透視的資料,您可以建構 RunPivotReportRequest 物件。建議您先使用以下請求參數:
- dateRanges 欄位中的有效項目。
- 「dimensions」欄位中至少有一個有效項目。
- 在 metrics 欄位中至少有一個有效項目。
- Pivots 欄位中至少有兩個有效的資料透視項目。
以下是含建議欄位的範例要求:
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_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
維度會指出每個事件的來源城市 (「巴黎」或「紐約」)。在報表要求中,您可以指定零個或多個維度。
尺寸必須在要求主體的尺寸欄位內定義。這些維度也必須列在 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
欄位,才能限制報表基數。
只要每個資料透視的 limit
參數乘積不超過 100,000 個,Data API v1 即可支援多個資料透視。
以下程式碼片段示範如何使用 offset
和 limit
欄位,擷取接下來五個 language
維度 (偏移值為 10):
{
"fieldNames": [
"language"
],
"offset": 10,
"limit": 5
}
篩選
與核心報表功能類似,如果需要資料透視報表要求使用維度篩選功能,則必須使用要求限定範圍的維度篩選器。
排序
您可以使用 Pivot 物件的 orderBys 欄位 (含有 OrderBy 物件清單),個別控制資料透視報表查詢的排序行為。
每個 OrderBy
都可以包含下列其中一項:
- DimensionOrderBy,依據維度的值將結果排序。
- MetricOrderBy:按照指標值排序結果。
- PivotOrderBy:用於資料透視查詢,並按照資料透視資料欄群組中的指標值排序結果。
這個範例顯示了資料透視定義程式碼片段,該程式碼片段以 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 方法的樞紐報告回應與 Core Reporting 方法 (例如 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 資料透視報表示範應用程式。