本節概述 Realtime Reporting API 方法的功能 Google Analytics Data API v1 的基本功能。如需 API 的詳細參考資料,請參閱 API 參考資料。
事件 傳送給 Google 數據分析即時報表會顯示一段時間內的事件和使用資料 範圍從現在到 30 分鐘前 (Google 可能需要 60 分鐘) Analytics 360 資源),且適用於 計算分數
即時報表僅支援部分維度和指標 與 Data API v1 的核心報表功能相比的結果。
與核心報表共用的功能
即時報表要求與核心報表要求的語意相同 有許多共同功能例如分頁、維度篩選器 和「使用者屬性」的行為都相同 做為核心報表請先熟悉 Data API v1 的核心報表功能總覽, 因為本文後續會著重介紹 即時報表要求。
檢舉要求
若要要求即時報表,您可以 RunRealtimeReportRequest 物件。建議您先從以下要求參數著手:
- 在「dimensions」欄位中至少一個有效項目。
- 在「metrics」欄位中至少有一個有效項目。
以下是包含建議欄位的要求範例。
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runRealtimeReport
{
"dimensions": [{ "name": "country" }],
"metrics": [{ "name": "activeUsers" }]
}
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.DimensionHeader; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.MetricHeader; import com.google.analytics.data.v1beta.Row; import com.google.analytics.data.v1beta.RunRealtimeReportRequest; import com.google.analytics.data.v1beta.RunRealtimeReportResponse; /** * Google Analytics Data API sample application demonstrating the creation of a realtime report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportSample" * }</pre> */ public class RunRealtimeReportSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = "YOUR-GA4-PROPERTY-ID"; sampleRunRealtimeReport(propertyId); } // Runs a realtime report on a Google Analytics 4 property. static void sampleRunRealtimeReport(String propertyId) throws Exception { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunRealtimeReportRequest request = RunRealtimeReportRequest.newBuilder() .setProperty("properties/" + propertyId) .addDimensions(Dimension.newBuilder().setName("country")) .addMetrics(Metric.newBuilder().setName("activeUsers")) .build(); // Make the request. RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request); printRunRealtimeReportResponse(response); } } // Prints results of a runRealReport call. static void printRunRealtimeReportResponse(RunRealtimeReportResponse response) { System.out.printf("%s rows received%n", response.getRowsList().size()); for (DimensionHeader header : response.getDimensionHeadersList()) { System.out.printf("Dimension header name: %s%n", header.getName()); } for (MetricHeader header : response.getMetricHeadersList()) { System.out.printf("Metric header name: %s (%s)%n", header.getName(), header.getType()); } System.out.println("Report result:"); for (Row row : response.getRowsList()) { System.out.printf( "%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue()); } } }
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunRealtimeReportRequest; use Google\Analytics\Data\V1beta\RunRealtimeReportResponse; /** * Runs a realtime report on a Google Analytics 4 property. * @param string $propertyId Your GA-4 Property ID */ function run_realtime_report(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunRealtimeReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'country'])]) ->setMetrics([new Metric(['name' => 'activeUsers'])]); $response = $client->runRealtimeReport($request); printRunRealtimeReportResponse($response); } /** * Print results of a runRealtimeReport call. * @param RunRealtimeReportResponse $response */ function printRunRealtimeReportResponse(RunRealtimeReportResponse $response) { printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)%s', $metricHeader->getName(), MetricType::name($metricHeader->getType()), PHP_EOL ); } 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 ( Dimension, Metric, RunRealtimeReportRequest, ) from run_report import print_run_report_response 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_realtime_report(property_id) def run_realtime_report(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a realtime report on a Google Analytics 4 property.""" client = BetaAnalyticsDataClient() request = RunRealtimeReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="country")], metrics=[Metric(name="activeUsers")], ) response = client.run_realtime_report(request) print_run_report_response(response)
Node.js
/** * TODO(developer): Uncomment this variable and replace with your GA4 * 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'); // Creates a client. const analyticsDataClient = new BetaAnalyticsDataClient(); // Runs a realtime report on a Google Analytics 4 property. async function runRealtimeReport() { const [response] = await analyticsDataClient.runRealtimeReport({ property: `properties/${propertyId}`, dimensions: [ { name: 'country', }, ], metrics: [ { name: 'activeUsers', }, ], }); printRunReportResponse(response); } runRealtimeReport(); // Prints results of a runReport call. function printRunReportResponse(response) { console.log(`${response.rowCount} rows received`); response.dimensionHeaders.forEach(dimensionHeader => { console.log(`Dimension header name: ${dimensionHeader.name}`); }); response.metricHeaders.forEach(metricHeader => { console.log( `Metric header name: ${metricHeader.name} (${metricHeader.type})` ); }); console.log('Report result:'); response.rows.forEach(row => { console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }
檢舉回應
即時報表回應 API 要求主要是標頭和列。標題由 DimensionHeaders 和 MetricHeaders 報表中會列出資料欄。每列都包含 DimensionValues 和 MetricValues 即可。在要求、標頭或標頭 和每一列一樣
以下是上述要求範例的回應範例:
{
"dimensionHeaders": [
{
"name": "country"
}
],
"metricHeaders": [
{
"name": "activeUsers",
"type": "TYPE_INTEGER"
}
],
"rows": [
{
"dimensionValues": [
{
"value": "Japan"
}
],
"metricValues": [
{
"value": "2541"
}
]
},
{
"dimensionValues": [
{
"value": "France"
}
],
"metricValues": [
{
"value": "12"
}
]
}
],
"rowCount": 2
}
尺寸
維度:描述事件性並分組
網站或應用程式舉例來說,city
維度會指出城市 (「巴黎」)
或「紐約」)。在報表請求中,您可以:
請指定零個或多個維度查看即時維度
,查看即時請求中可用的 API 維度名稱完整清單。
例如,這項要求會在兩個維度欄中將「活躍使用者」分組:
HTTP
POST https://analyticsdata.googleapis.com/v1beta/property/GA_PROPERTY_ID:runRealtimeReport
{
"dimensions": [
{
"name": "country"
},
{
"name": "city"
}
],
"metrics": [{ "name": "activeUsers" }]
}
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunRealtimeReportRequest; import com.google.analytics.data.v1beta.RunRealtimeReportResponse; /** * Google Analytics Data API sample application demonstrating the creation of a realtime report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportWithMultipleDimensionsSample" * }</pre> */ public class RunRealtimeReportWithMultipleDimensionsSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = "YOUR-GA4-PROPERTY-ID"; sampleRunRealtimeReportWithMultipleDimensions(propertyId); } // Runs a realtime report on a Google Analytics 4 property. static void sampleRunRealtimeReportWithMultipleDimensions(String propertyId) throws Exception { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunRealtimeReportRequest request = RunRealtimeReportRequest.newBuilder() .setProperty("properties/" + propertyId) .addDimensions(Dimension.newBuilder().setName("country")) .addDimensions(Dimension.newBuilder().setName(("city"))) .addMetrics(Metric.newBuilder().setName("activeUsers")) .build(); // Make the request. RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request); // Prints the response using a method in RunRealtimeReportSample.java RunRealtimeReportSample.printRunRealtimeReportResponse(response); } } }
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunRealtimeReportRequest; use Google\Analytics\Data\V1beta\RunRealtimeReportResponse; /** * Runs a realtime report on a Google Analytics 4 property. * @param string $propertyId Your GA-4 Property ID */ function run_realtime_report_with_multiple_dimensions(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunRealtimeReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([ new Dimension(['name' => 'country']), new Dimension(['name' => 'city']), ]) ->setMetrics([new Metric(['name' => 'activeUsers'])]); $response = $client->runRealtimeReport($request); printRunRealtimeReportWithMultipleDimensionsResponse($response); } /** * Print results of a runRealtimeReport call. * @param RunRealtimeReportResponse $response */ function printRunRealtimeReportWithMultipleDimensionsResponse(RunRealtimeReportResponse $response) { printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)%s', $metricHeader->getName(), MetricType::name($metricHeader->getType()), PHP_EOL ); } 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 ( Dimension, Metric, RunRealtimeReportRequest, ) from run_report import print_run_report_response 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_realtime_report_with_multiple_dimensions(property_id) def run_realtime_report_with_multiple_dimensions(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a realtime report on a Google Analytics 4 property.""" client = BetaAnalyticsDataClient() request = RunRealtimeReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="country"), Dimension(name="city")], metrics=[Metric(name="activeUsers")], ) response = client.run_realtime_report(request) print_run_report_response(response)
Node.js
/** * TODO(developer): Uncomment this variable and replace with your GA4 * 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 realtime report on a Google Analytics 4 property. async function runRealtimeReportWithMultipleDimensions() { const [response] = await analyticsDataClient.runRealtimeReport({ property: `properties/${propertyId}`, dimensions: [ { name: 'country', }, { name: 'city', }, ], metrics: [ { name: 'activeUsers', }, ], }); printRunReportResponse(response); } runRealtimeReportWithMultipleDimensions(); // Prints results of a runReport call. function printRunReportResponse(response) { console.log(`${response.rowCount} rows received`); response.dimensionHeaders.forEach(dimensionHeader => { console.log(`Dimension header name: ${dimensionHeader.name}`); }); response.metricHeaders.forEach(metricHeader => { console.log( `Metric header name: ${metricHeader.name} (${metricHeader.type})` ); }); console.log('Report result:'); response.rows.forEach(row => { console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }
舉例來說,報表回應中的一列可能會包含以下內容。這一列 表示網站或應用程式有 47 位活躍使用者,且有來自 Cape 的事件 過去 30 分鐘內的南非鄉。
"rows": [
...
{
"dimensionValues": [
{
"value": "South Africa"
},
{
"value": "Cape Town"
}
],
"metricValues": [
{
"value": "47"
}
]
},
...
],
指標
指標是針對下列項目的量化評估資料: 網站或應用程式在報表要求中,您可以指定一或多個指標。 如需 API 的完整清單,請參閱即時指標 要求中提供的指標名稱。
舉例來說,這項要求會顯示按維度分組的兩個指標
unifiedScreenName
:
HTTP
POST https://analyticsdata.googleapis.com/v1beta/property/GA_PROPERTY_ID:runRealtimeReport
{
"dimensions": [{ "name": "unifiedScreenName" }],
"metrics": [
{
"name": "screenPageViews"
},
{
"name": "keyEvents"
}
],
}
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunRealtimeReportRequest; import com.google.analytics.data.v1beta.RunRealtimeReportResponse; /** * Google Analytics Data API sample application demonstrating the creation of a realtime report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportWithMultipleMetricsSample" * }</pre> */ public class RunRealtimeReportWithMultipleMetricsSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = "YOUR-GA4-PROPERTY-ID"; sampleRunRealtimeReportWithMultipleMetrics(propertyId); } // Runs a realtime report on a Google Analytics 4 property. static void sampleRunRealtimeReportWithMultipleMetrics(String propertyId) throws Exception { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunRealtimeReportRequest request = RunRealtimeReportRequest.newBuilder() .setProperty("properties/" + propertyId) .addDimensions(Dimension.newBuilder().setName("unifiedScreenName")) .addMetrics(Metric.newBuilder().setName(("screenPageViews"))) .addMetrics(Metric.newBuilder().setName("keyEvents")) .build(); // Make the request. RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request); // Prints the response using a method in RunRealtimeReportSample.java RunRealtimeReportSample.printRunRealtimeReportResponse(response); } } }
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunRealtimeReportRequest; use Google\Analytics\Data\V1beta\RunRealtimeReportResponse; /** * Runs a realtime report on a Google Analytics 4 property. * @param string $propertyId Your GA-4 Property ID */ function run_realtime_report_with_multiple_metrics(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunRealtimeReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'unifiedScreenName'])]) ->setMetrics([ new Metric(['name' => 'screenPageViews']), new Metric(['name' => 'keyEvents']), ]); $response = $client->runRealtimeReport($request); printRunRealtimeReportWithMultipleMetricsResponse($response); } /** * Print results of a runRealtimeReport call. * @param RunRealtimeReportResponse $response */ function printRunRealtimeReportWithMultipleMetricsResponse(RunRealtimeReportResponse $response) { printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)%s', $metricHeader->getName(), MetricType::name($metricHeader->getType()), PHP_EOL ); } 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 ( Dimension, Metric, RunRealtimeReportRequest, ) from run_report import print_run_report_response 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_realtime_report_with_multiple_metrics(property_id) def run_realtime_report_with_multiple_metrics(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a realtime report on a Google Analytics 4 property.""" client = BetaAnalyticsDataClient() request = RunRealtimeReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="unifiedScreenName")], metrics=[Metric(name="screenPageViews"), Metric(name="keyEvents")], ) response = client.run_realtime_report(request) print_run_report_response(response)
Node.js
/** * TODO(developer): Uncomment this variable and replace with your GA4 * 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'); // Creates a client. const analyticsDataClient = new BetaAnalyticsDataClient(); // Runs a realtime report on a Google Analytics 4 property. async function runRealtimeReportWithMultipleMetrics() { const [response] = await analyticsDataClient.runRealtimeReport({ // The property parameter value must be in the form `properties/1234` // where `1234` is a GA4 property Id. property: `properties/${propertyId}`, dimensions: [ { name: 'unifiedScreenName', }, ], metrics: [ { name: 'screenPageViews', }, { name: 'keyEvents', }, ], }); printRunReportResponse(response); } runRealtimeReportWithMultipleMetrics(); // Prints results of a runReport call. function printRunReportResponse(response) { console.log(`${response.rowCount} rows received`); response.dimensionHeaders.forEach(dimensionHeader => { console.log(`Dimension header name: ${dimensionHeader.name}`); }); response.metricHeaders.forEach(metricHeader => { console.log( `Metric header name: ${metricHeader.name} (${metricHeader.type})` ); }); console.log('Report result:'); response.rows.forEach(row => { console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }
做為範例,報表回應中的一列可能包含以下內容。這一列
是指 main_menu
的網頁標題 (網頁) 或畫面名稱 (應用程式)。
在過去 30 分鐘內獲得 257 次觀看和 72 個重要事件。
"rows": [
...
{
"dimensionValues": [
{
"value": "main_menu"
}
],
"metricValues": [
{
"value": "257"
},
{
"value": "72"
}
]
},
...
],
分鐘範圍
在即時報表請求中,您可以使用 minuteRanges 欄位,用於指定 Minute Ranges 要讀取的事件資料查詢中最多可以使用兩個不同的分鐘範圍。如果 查詢中沒有分鐘範圍規格, 會使用最近 30 分鐘的資料
例如,下方的請求會分別顯示兩分鐘的活躍使用者人數 範圍:
- 範圍 #1:從 4 分鐘前開始,直到現在為止。
範圍 #2:從 29 分鐘前開始,直到 25 分鐘前 (含)。
HTTP
POST https://analyticsdata.googleapis.com/v1beta/property/GA_PROPERTY_ID:runRealtimeReport
{
"metrics": [
{
"name": "activeUsers"
}
],
"minuteRanges": [
{
"name": "0-4 minutes ago",
"startMinutesAgo": 4,
},
{
"name": "25-29 minutes ago",
"startMinutesAgo": 29,
"endMinutesAgo": 25,
}
],
}
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.MinuteRange; import com.google.analytics.data.v1beta.RunRealtimeReportRequest; import com.google.analytics.data.v1beta.RunRealtimeReportResponse; /** * Google Analytics Data API sample application demonstrating the creation of a realtime report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport * for more information. * * <p>Before you start the application, please review the comments starting with "TODO(developer)" * and update the code to use correct values. * * <p>To run this sample using Maven: * * <pre>{@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportWithMinuteRangesSample" * }</pre> */ public class RunRealtimeReportWithMinuteRangesSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = "YOUR-GA4-PROPERTY-ID"; sampleRunRealtimeReportWithMinuteRanges(propertyId); } // Runs a realtime report on a Google Analytics 4 property. static void sampleRunRealtimeReportWithMinuteRanges(String propertyId) throws Exception { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunRealtimeReportRequest request = RunRealtimeReportRequest.newBuilder() .setProperty("properties/" + propertyId) .addMetrics(Metric.newBuilder().setName(("activeUsers"))) .addMinuteRanges( MinuteRange.newBuilder().setName("0-4 minutes ago").setStartMinutesAgo(4)) .addMinuteRanges( MinuteRange.newBuilder() .setName("25-29 minutes ago") .setEndMinutesAgo(29) .setEndMinutesAgo(25)) .build(); // Make the request. RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request); // Prints the response using a method in RunRealtimeReportSample.java RunRealtimeReportSample.printRunRealtimeReportResponse(response); } } }
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\MinuteRange; use Google\Analytics\Data\V1beta\RunRealtimeReportRequest; use Google\Analytics\Data\V1beta\RunRealtimeReportResponse; /** * Runs a realtime report on a Google Analytics 4 property. Dimensions field is * omitted in the query, which results in total values of active users returned * for each minute range in the report. * * Note the `dateRange` dimension added to the report response automatically as * a result of querying multiple minute ranges. * @param string $propertyId Your GA-4 Property ID */ function run_realtime_report_with_minute_ranges(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunRealtimeReportRequest()) ->setProperty('properties/' . $propertyId) ->setMetrics([ new Metric(['name' => 'activeUsers']), ]) ->setMinuteRanges([ new MinuteRange(['name' => '0-4 minutes ago', 'start_minutes_ago' => 4]), new MinuteRange(['name' => '25-29 minutes ago', 'start_minutes_ago' => 29, 'end_minutes_ago' => 25]), ]); $response = $client->runRealtimeReport($request); printRunRealtimeReportWithMinuteRangesResponse($response); } /** * Print results of a runRealtimeReport call. * @param RunRealtimeReportResponse $response */ function printRunRealtimeReportWithMinuteRangesResponse(RunRealtimeReportResponse $response) { printf('%s rows received%s', $response->getRowCount(), PHP_EOL); foreach ($response->getDimensionHeaders() as $dimensionHeader) { printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); } foreach ($response->getMetricHeaders() as $metricHeader) { printf( 'Metric header name: %s (%s)%s', $metricHeader->getName(), MetricType::name($metricHeader->getType()), PHP_EOL ); } 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 ( Metric, MinuteRange, RunRealtimeReportRequest, ) from run_report import print_run_report_response 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_realtime_report_with_minute_ranges(property_id) def run_realtime_report_with_minute_ranges(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a realtime report on a Google Analytics 4 property. Dimensions field is omitted in the query, which results in total values of active users returned for each minute range in the report. Note the `dateRange` dimension added to the report response automatically as a result of querying multiple minute ranges. """ client = BetaAnalyticsDataClient() request = RunRealtimeReportRequest( property=f"properties/{property_id}", metrics=[Metric(name="activeUsers")], minute_ranges=[ MinuteRange(name="0-4 minutes ago", start_minutes_ago=4), MinuteRange( name="25-29 minutes ago", start_minutes_ago=29, end_minutes_ago=25 ), ], ) response = client.run_realtime_report(request) print_run_report_response(response)
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 report using two date ranges. async function runRealtimeReportWithMinuteRanges() { const [response] = await analyticsDataClient.runRealtimeReport({ property: `properties/${propertyId}`, minuteRanges: [ { name: '0-4 minutes ago', startMinutesAgo: 4, endMinutesAgo: 0, }, { name: '25-29 minutes ago', startMinutesAgo: 29, endMinutesAgo: 25, }, ], metrics: [ { name: 'activeUsers', }, ], }); printRunReportResponse(response); } runRealtimeReportWithMinuteRanges(); // Prints results of a runReport call. function printRunReportResponse(response) { console.log(`${response.rowCount} rows received`); response.dimensionHeaders.forEach(dimensionHeader => { console.log(`Dimension header name: ${dimensionHeader.name}`); }); response.metricHeaders.forEach(metricHeader => { console.log( `Metric header name: ${metricHeader.name} (${metricHeader.type})` ); }); console.log('Report result:'); response.rows.forEach(row => { console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }
以下是查詢的完整回應範例。請注意,
已自動將 dateRange
個維度加進報表回應
產生的結果。
{
"dimensionHeaders": [
{
"name": "dateRange"
}
],
"metricHeaders": [
{
"name": "activeUsers",
"type": "TYPE_INTEGER"
}
],
"rows": [
{
"dimensionValues": [
{
"value": "0-4 minutes ago"
}
],
"metricValues": [
{
"value": "16"
}
]
},
{
"dimensionValues": [
{
"value": "25-29 minutes ago"
}
],
"metricValues": [
{
"value": "14"
}
]
}
],
"rowCount": 2,
"kind": "analyticsData#runRealtimeReport"
}