创建实时报告

本文简要介绍了 Google Analytics Data API v1 的 Realtime Reporting API Method 功能。如需查看该 API 的详细参考文档,请参阅 API 参考文档

事件在发送到 Google Analytics 几秒钟后就会显示在实时报告中。“实时”报告会显示从当前时间到 30 分钟前(Google Analytics 360 版媒体资源最多可显示 60 分钟前)的时间段内的事件和使用情况数据,可用于网站访问者实时计数器等应用。

与 Data API v1 的核心报告功能相比,实时报告支持的维度和指标只有一小部分。

与核心报告共享的功能

对于许多共享功能,实时报告请求与 Core 报告请求具有相同的语义。例如,分页维度过滤条件用户属性在“实时”报告中的运作方式与核心报告中的运作方式相同。请熟悉 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 请求的实时报告响应主要由标题和行组成。标题由 DimensionHeadersMetricHeaders 组成,其中列出了报告中的列。每行都包含报告中各列的 DimensionValuesMetricValues。请求、标题和每行中的列排序保持一致。

以下是上文示例请求的示例响应:

{   "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}`       );     });   }

举例来说,报告响应中的行可能包含以下内容。这行数据表示,过去 30 分钟内,您的网站或应用有 47 位活跃用户,并且有来自南非开普敦的事件。

"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 字段指定要读取的事件数据的分钟范围。一个查询中最多可以使用两个单独的分钟范围。如果查询中未指定分钟范围,系统将使用过去 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"   }