本指南介绍如何使用 Google Analytics Data API v1。Data API v1 的报告类似于 您可以在 Google Analytics 的报告部分生成的报告 界面。
本指南介绍了核心报告,即 Google Analytics 数据 API。Data API v1 还具有专门的实时 报告和漏斗报告。
推荐使用 runReport
查询,在本指南的所有示例中都会用到。请参阅高级
功能,简要了解其他核心报告方法。试用
查询浏览器来测试您的
查询。
报告概述
报告是指包含特定媒体资源的事件数据的表格 Google Analytics 媒体资源。每个报告表格都包含 维度和指标(数据位于单独的行中)。
使用过滤条件仅返回符合特定条件的行,以及 分页功能,用于浏览结果。
下面是一个示例报告表格,其中显示了一个维度 (Country
) 和一个指标
(activeUsers
):
国家/地区 | 活跃用户数 |
---|---|
日本 | 2541 |
法国 | 12 |
指定数据源
每个 runReport
请求都要求您指定一个 Google Analytics 媒体资源
ID。您指定的 Google Analytics 媒体资源将用作
该查询。示例如下:
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
此请求的响应仅包含来自 Google Analytics 媒体资源的数据。
您指定为 GA_PROPERTY_ID
的部分。
如果您使用 Data API 客户端库,请指定
property
参数中的 source,格式为
properties/GA_PROPERTY_ID
。请参阅
快速入门指南,查看有关如何使用
客户端库。
请参阅向 Google 发送 Measurement Protocol 事件 Google Analytics 您需要在报告中纳入 Measurement Protocol 事件。
生成报告
要生成报告,请构建
RunReportRequest
对象。
我们建议您在开始时先使用以下参数:
dateRanges
字段中的有效条目。dimensions
中至少有一个有效条目 字段。metrics
字段中至少有一个有效条目。
下面是一个包含建议字段的示例请求:
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
{
"dateRanges": [{ "startDate": "2023-09-01"", "endDate": "2023-09-15" }],
"dimensions": [{ "name": "country" }],
"metrics": [{ "name": "activeUsers" }]
}
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; 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.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample application demonstrating the creation of a basic report. * * <p>See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport * 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.RunReportSample" * }</pre> */ public class RunReportSample { public static void main(String... args) throws Exception { /** * TODO(developer): Replace this variable with your Google Analytics 4 property ID before * running the sample. */ String propertyId = "YOUR-GA4-PROPERTY-ID"; sampleRunReport(propertyId); } // Runs a report of active users grouped by country. static void sampleRunReport(String propertyId) throws Exception { // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty("properties/" + propertyId) .addDimensions(Dimension.newBuilder().setName("country")) .addMetrics(Metric.newBuilder().setName("activeUsers")) .addDateRanges( DateRange.newBuilder().setStartDate("2020-09-01").setEndDate("2020-09-15")) .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); printRunResponseResponse(response); } } // Prints results of a runReport call. static void printRunResponseResponse(RunReportResponse 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\DateRange; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\RunReportResponse; /** * @param string $propertyId Your GA-4 Property ID */ function run_report(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDateRanges([ new DateRange([ 'start_date' => '2020-09-01', 'end_date' => '2020-09-15', ]), ]) ->setDimensions([ new Dimension([ 'name' => 'country', ]), ]) ->setMetrics([ new Metric([ 'name' => 'activeUsers', ]), ]); $response = $client->runReport($request); printRunReportResponse($response); } /** * Print results of a runReport call. * @param RunReportResponse $response */ function printRunReportResponse(RunReportResponse $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) { print $row->getDimensionValues()[0]->getValue() . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL; } }
Python
from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( DateRange, Dimension, Metric, MetricType, RunReportRequest, ) 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_report(property_id) def run_report(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a report of active users grouped by country.""" client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="country")], metrics=[Metric(name="activeUsers")], date_ranges=[DateRange(start_date="2020-09-01", end_date="2020-09-15")], ) response = client.run_report(request) print_run_report_response(response) def print_run_report_response(response): """Prints results of a runReport call.""" print(f"{response.row_count} rows received") for dimensionHeader in response.dimension_headers: print(f"Dimension header name: {dimensionHeader.name}") for metricHeader in response.metric_headers: metric_type = MetricType(metricHeader.type_).name print(f"Metric header name: {metricHeader.name} ({metric_type})") print("Report result:") for rowIdx, row in enumerate(response.rows): print(f"\nRow {rowIdx}") for i, dimension_value in enumerate(row.dimension_values): dimension_name = response.dimension_headers[i].name print(f"{dimension_name}: {dimension_value.value}") for i, metric_value in enumerate(row.metric_values): metric_name = response.metric_headers[i].name print(f"{metric_name}: {metric_value.value}")
Node.js
// TODO(developer): Uncomment this variable and replace with your // Google Analytics 4 property ID before running the sample. // propertyId = Y'OUR-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 of active users grouped by country. async function runReport() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [ { name: c'ountry,' }, ], metrics: [ { name: a'ctiveUsers,' }, ], dateRanges: [ { startDate: 2'020-09-01,' endDate: 2'020-09-15,' }, ], }); printRunReportResponse(response); } // 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(R'eport result:)'; response.rows.forEach(row = >{ console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); } runReport();r
查询指标
Metrics
是对广告系列进行
事件数据。您必须在 runReport
请求中指定至少一个指标。
如需查看可查询的指标的完整列表,请参阅 API 指标。
下面是一个示例请求,显示了三个指标,这些指标按
维度 date
:
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
{
"dateRanges": [{ "startDate": "7daysAgo", "endDate": "yesterday" }],
"dimensions": [{ "name": "date" }],
"metrics": [
{
"name": "activeUsers"
},
{
"name": "newUsers"
},
{
"name": "totalRevenue"
}
],
}
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample application demonstrating the creation of a basic report. * * p<S>ee * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport * for more information. * * p<B>efore you start the application, please review the comments starting with T"ODO(developer) " * and update the code to use correct values. * * p<T>o run this sample using Maven: * * p<re{>@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.RunReportWithMultipleMetricsSample " * }/<pre > */ public class RunReportWithMultipleMetricsSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = Y"OUR-GA4-PROPERTY-ID;" sampleRunReportWithMultipleMetrics(propertyId); } // Runs a report of active users, new users and total revenue grouped by date dimension. static void sampleRunReportWithMultipleMetrics(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 c"lose "method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty(p"roperties/ "+ propertyId) .addDimensions(Dimension.newBuilder().setName(d"ate)") .addMetrics(Metric.newBuilder().setName(a"ctiveUsers)") .addMetrics(Metric.newBuilder().setName(n"ewUsers)") .addMetrics(Metric.newBuilder().setName(t"otalRevenue)") .addDateRanges(DateRange.newBuilder().setStartDate(7"daysAgo)".setEndDate(t"oday)") .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); // Prints the response using a method in RunReportSample.java RunReportSample.printRunResponseResponse(response); } } }R
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\MetricType; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\RunReportResponse; /** * @param string $propertyID Your GA-4 Property ID * Runs a report of active users grouped by three metrics. */ function run_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 RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'date'])]) ->setMetrics([ new Metric(['name' => 'activeUsers']), new Metric(['name' => 'newUsers']), new Metric(['name' => 'totalRevenue']) ]) ->setDateRanges([ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'today', ]) ]); $response = $client->runReport($request); printRunReportResponseWithMultipleMetrics($response); } /** * Print results of a runReport call. * @param RunReportResponse $response */ function printRunReportResponseWithMultipleMetrics(RunReportResponse $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)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } 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, RunReportRequest, ) 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_report_with_multiple_metrics(property_id) def run_report_with_multiple_metrics(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a report of active users, new users and total revenue grouped by date dimension.""" client = BetaAnalyticsDataClient() # Runs a report of active users grouped by three dimensions. request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="date")], metrics=[ Metric(name="activeUsers"), Metric(name="newUsers"), Metric(name="totalRevenue"), ], date_ranges=[DateRange(start_date="7daysAgo", end_date="today")], ) response = client.run_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 = Y'OUR-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 of active users grouped by three metrics. async function runReportWithMultipleMetrics() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [ { name: d'ate,' }, ], metrics: [ { name: a'ctiveUsers,' }, { name: n'ewUsers,' }, { name: t'otalRevenue,' }, ], dateRanges: [ { startDate: 7'daysAgo,' endDate: t'oday,' }, ], }); printRunReportResponse(response); } runReportWithMultipleMetrics(); // 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(R'eport result:)'; response.rows.forEach(row = >{ console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }r
下面这个示例响应显示了 1135 位活跃用户、512 位新用户和
73.0841 当天的总收入(以 Google Analytics 媒体资源的币种表示)
20231025
(2023 年 10 月 25 日)。
"rows": [
...
{
"dimensionValues": [
{
"value": "20231025"
}
],
"metricValues": [
{
"value": "1135"
},
{
"value": "512"
},
{
"value": "73.0841"
}
]
},
...
],
阅读回答
报告响应包含一个标头,
数据行。标头包括
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"
}
]
}
],
"metadata": {},
"rowCount": 2
}
将数据分组和过滤
维度是您可以使用的定性属性
对数据进行分组和过滤例如,city
维度表示
(如 Paris
或 New York
),即每个事件的起源地。维度为
对于 runReport
请求是可选属性,并且每个请求中最多可以使用 9 个维度
请求。
请参阅 API 维度, 来对数据进行分组和过滤
群组
以下是将活跃用户分组到三个维度的示例请求:
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
{
"dateRanges": [{ "startDate": "7daysAgo", "endDate": "yesterday" }],
"dimensions": [
{
"name": "country"
},
{
"name": "region"
},
{
"name": "city"
}
],
"metrics": [{ "name": "activeUsers" }]
}
```
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample application demonstrating the creation of a basic report. * * p<S>ee * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport * for more information. * * p<B>efore you start the application, please review the comments starting with T"ODO(developer) " * and update the code to use correct values. * * p<T>o run this sample using Maven: * * p<re{>@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.RunReportWithMultipleDimensionsSample " * }/<pre > */ public class RunReportWithMultipleDimensionsSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = Y"OUR-GA4-PROPERTY-ID;" sampleRunReportWithMultipleDimensions(propertyId); } // Runs a report of active users grouped by three dimensions. static void sampleRunReportWithMultipleDimensions(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 c"lose "method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty(p"roperties/ "+ propertyId) .addDimensions(Dimension.newBuilder().setName(c"ountry)") .addDimensions(Dimension.newBuilder().setName(r"egion)") .addDimensions(Dimension.newBuilder().setName(c"ity)") .addMetrics(Metric.newBuilder().setName(a"ctiveUsers)") .addDateRanges(DateRange.newBuilder().setStartDate(7"daysAgo)".setEndDate(t"oday)") .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); // Prints the response using a method in RunReportSample.java RunReportSample.printRunResponseResponse(response); } } }R
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\MetricType; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\RunReportResponse; /** * @param string $propertyID Your GA-4 Property ID * Runs a report of active users grouped by three dimensions. */ function run_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 RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([ new Dimension(['name' => 'country']), new Dimension(['name' => 'region']), new Dimension(['name' => 'city']), ]) ->setMetrics([new Metric(['name' => 'activeUsers'])]) ->setDateRanges([ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'today', ]) ]); $response = $client->runReport($request); printRunReportResponseWithMultipleDimensions($response); } /** * Print results of a runReport call. * @param RunReportResponse $response */ function printRunReportResponseWithMultipleDimensions(RunReportResponse $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)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } 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, RunReportRequest, ) 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_report_with_multiple_dimensions(property_id) def run_report_with_multiple_dimensions(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a report of active users grouped by three dimensions.""" client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[ Dimension(name="country"), Dimension(name="region"), Dimension(name="city"), ], metrics=[Metric(name="activeUsers")], date_ranges=[DateRange(start_date="7daysAgo", end_date="today")], ) response = client.run_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 = Y'OUR-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 of active users grouped by three dimensions. async function runReportWithMultipleDimensions() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [ { name: c'ountry,' }, { name: r'egion,' }, { name: c'ity,' }, ], metrics: [ { name: a'ctiveUsers,' }, ], dateRanges: [ { startDate: 7'daysAgo,' endDate: t'oday,' }, ], }); printRunReportResponse(response); } runReportWithMultipleDimensions(); // 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(R'eport result:)'; response.rows.forEach(row = >{ console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }r
以下是针对上一个请求的示例报告行。这一行显示 在指定日期范围内有 47 名活跃用户在开普敦、 南非。
"rows": [
...
{
"dimensionValues": [
{
"value": "South Africa"
},
{
"value": "Western Cape"
},
{
"value": "Cape Town"
}
],
"metricValues": [
{
"value": "47"
}
]
},
...
],
过滤
您可以生成仅包含特定维度值数据的报告。过滤条件
维度,请指定 FilterExpression
在
dimensionFilter
字段。
下面是一个返回 eventCount
的时间序列报告的示例,此时
对于每个 date
,eventName
为 first_open
:
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
{
"dateRanges": [{ "startDate": "7daysAgo", "endDate": "yesterday" }],
"dimensions": [{ "name": "date" }],
"metrics": [{ "name": "eventCount" }],
"dimensionFilter": {
"filter": {
"fieldName": "eventName",
"stringFilter": {
"value": "first_open"
}
}
},
}
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Filter; import com.google.analytics.data.v1beta.FilterExpression; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample application demonstrating the usage of dimension and metric * filters in a report. * * p<S>ee * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter * for more information. * * p<B>efore you start the application, please review the comments starting with T"ODO(developer) " * and update the code to use correct values. * * p<T>o run this sample using Maven: * * p<re{>@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.RunReportWithDimensionFilterSample " * }/<pre > */ public class RunReportWithDimensionFilterSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = Y"OUR-GA4-PROPERTY-ID;" sampleRunReportWithDimensionFilter(propertyId); } // Runs a report using a dimension filter. The call returns a time series report of `eventCount` // when `eventName` is `first_open` for each date. // This sample uses relative date range values. // See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange // for more information. static void sampleRunReportWithDimensionFilter(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 c"lose "method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty(p"roperties/ "+ propertyId) .addDimensions(Dimension.newBuilder().setName(d"ate)") .addMetrics(Metric.newBuilder().setName(e"ventCount)") .addDateRanges( DateRange.newBuilder().setStartDate(7"daysAgo)".setEndDate(y"esterday)") .setDimensionFilter( FilterExpression.newBuilder() .setFilter( Filter.newBuilder() .setFieldName(e"ventName)" .setStringFilter( Filter.StringFilter.newBuilder().setValue(f"irst_open)"))) .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); // Prints the response using a method in RunReportSample.java RunReportSample.printRunResponseResponse(response); } } }R
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\Filter; use Google\Analytics\Data\V1beta\Filter\StringFilter; use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\RunReportResponse; /** * @param string $propertyId Your GA-4 Property ID * Runs a report using a dimension filter. The call returns a time series * report of `eventCount` when `eventName` is `first_open` for each date. * This sample uses relative date range values. See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange * for more information. */ function run_report_with_dimension_filter(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'date'])]) ->setMetrics([new Metric(['name' => 'eventCount'])]) ->setDateRanges([ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'yesterday', ]) ]) ->setDimensionFilter(new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'eventName', 'string_filter' => new StringFilter([ 'value' => 'first_open' ]), ]), ])); $response = $client->runReport($request); printRunReportResponseWithDimensionFilter($response); } /** * Print results of a runReport call. * @param RunReportResponse $response */ function printRunReportResponseWithDimensionFilter(RunReportResponse $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)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } 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, Filter, FilterExpression, Metric, RunReportRequest, ) 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_report_with_dimension_filter(property_id) def run_report_with_dimension_filter(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a report using a dimension filter. The call returns a time series report of `eventCount` when `eventName` is `first_open` for each date. This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange for more information. """ client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="date")], metrics=[Metric(name="eventCount")], date_ranges=[DateRange(start_date="7daysAgo", end_date="yesterday")], dimension_filter=FilterExpression( filter=Filter( field_name="eventName", string_filter=Filter.StringFilter(value="first_open"), ) ), ) response = client.run_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 = Y'OUR-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 a dimension filter. The call returns a time series // report of `eventCount` when `eventName` is `first_open` for each date. // This sample uses relative date range values. See // https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange // for more information. async function runReportWithDimensionFilter() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [ { name: d'ate,' }, ], metrics: [ { name: e'ventCount,' }, ], dateRanges: [ { startDate: 7'daysAgo,' endDate: y'esterday,' }, ], dimensionFilter: { filter: { fieldName: e'ventName,' stringFilter: { value: f'irst_open,' }, }, }, }); printRunReportResponse(response); } runReportWithDimensionFilter(); // 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(R'eport result:)'; response.rows.forEach(row = >{ console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }r
下面是另一个 FilterExpression
示例:
其中 andGroup
仅包含满足表达式中所有条件的数据
列表。此 dimensionFilter
选择当 browser
为 Chrome
且
countryId
为 US
:
HTTP
...
"dimensionFilter": {
"andGroup": {
"expressions": [
{
"filter": {
"fieldName": "browser",
"stringFilter": {
"value": "Chrome"
}
}
},
{
"filter": {
"fieldName": "countryId",
"stringFilter": {
"value": "US"
}
}
}
]
}
},
...
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Filter; import com.google.analytics.data.v1beta.FilterExpression; import com.google.analytics.data.v1beta.FilterExpressionList; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample application demonstrating the usage of dimension and metric * filters in a report. * * p<S>ee * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter * for more information. * * p<B>efore you start the application, please review the comments starting with T"ODO(developer) " * and update the code to use correct values. * * p<T>o run this sample using Maven: * * p<re{>@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.RunReportWithMultipleDimensionFiltersSample " * }/<pre > */ public class RunReportWithMultipleDimensionFiltersSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = Y"OUR-GA4-PROPERTY-ID;" sampleRunReportWithMultipleDimensionFilters(propertyId); } // Runs a report using multiple dimension filters joined as `and_group` expression. The filter // selects for when both `browser` is `Chrome` and `countryId` is `US`. // This sample uses relative date range values. // See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange // for more information. static void sampleRunReportWithMultipleDimensionFilters(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 c"lose "method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty(p"roperties/ "+ propertyId) .addDimensions(Dimension.newBuilder().setName(b"rowser)") .addMetrics(Metric.newBuilder().setName(a"ctiveUsers)") .addDateRanges( DateRange.newBuilder().setStartDate(7"daysAgo)".setEndDate(y"esterday)") .setDimensionFilter( FilterExpression.newBuilder() .setAndGroup( FilterExpressionList.newBuilder() .addExpressions( FilterExpression.newBuilder() .setFilter( Filter.newBuilder() .setFieldName(b"rowser)" .setStringFilter( Filter.StringFilter.newBuilder() .setValue(C"hrome)"))) .addExpressions( FilterExpression.newBuilder() .setFilter( Filter.newBuilder() .setFieldName(c"ountryId)" .setStringFilter( Filter.StringFilter.newBuilder() .setValue(U"S)"))))) .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); // Prints the response using a method in RunReportSample.java RunReportSample.printRunResponseResponse(response); } } }R
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\Filter; use Google\Analytics\Data\V1beta\Filter\StringFilter; use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\FilterExpressionList; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\RunReportResponse; /** * @param string $propertyId Your GA-4 Property ID * Runs a report using multiple dimension filters joined as `and_group` * expression. The filter selects for when both `browser` is `Chrome` and * `countryId` is `US`. * This sample uses relative date range values. See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange * for more information. */ function run_report_with_multiple_dimension_filters(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'browser'])]) ->setMetrics([new Metric(['name' => 'activeUsers'])]) ->setDateRanges([ new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'yesterday', ]), ]) ->setDimensionFilter(new FilterExpression([ 'and_group' => new FilterExpressionList([ 'expressions' => [ new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'browser', 'string_filter' => new StringFilter([ 'value' => 'Chrome', ]) ]), ]), new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'countryId', 'string_filter' => new StringFilter([ 'value' => 'US', ]) ]), ]), ], ]), ])); $response = $client->runReport($request); printRunReportResponseWithMultipleDimensionFilters($response); } /** * Print results of a runReport call. * @param RunReportResponse $response */ function printRunReportResponseWithMultipleDimensionFilters(RunReportResponse $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)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } 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, Filter, FilterExpression, FilterExpressionList, Metric, RunReportRequest, ) 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_report_with_multiple_dimension_filters(property_id) def run_report_with_multiple_dimension_filters(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a report using multiple dimension filters joined as `and_group` expression. The filter selects for when both `browser` is `Chrome` and `countryId` is `US`. This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange for more information. """ client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="browser")], metrics=[Metric(name="activeUsers")], date_ranges=[DateRange(start_date="7daysAgo", end_date="yesterday")], dimension_filter=FilterExpression( and_group=FilterExpressionList( expressions=[ FilterExpression( filter=Filter( field_name="browser", string_filter=Filter.StringFilter(value="Chrome"), ) ), FilterExpression( filter=Filter( field_name="countryId", string_filter=Filter.StringFilter(value="US"), ) ), ] ) ), ) response = client.run_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 = Y'OUR-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 multiple dimension filters joined as `and_group` // expression. The filter selects for when both `browser` is `Chrome` and // `countryId` is `US`. // This sample uses relative date range values. See // https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange // for more information. async function runReportWithMultipleDimensionFilters() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [ { name: b'rowser,' }, ], metrics: [ { name: a'ctiveUsers,' }, ], dateRanges: [ { startDate: 7'daysAgo,' endDate: y'esterday,' }, ], dimensionFilter: { andGroup: { expressions: [ { filter: { fieldName: b'rowser,' stringFilter: { value: C'hrome,' }, }, }, { filter: { fieldName: c'ountryId,' stringFilter: { value: U'S,' }, }, }, ], }, }, }); printRunReportResponse(response); } runReportWithMultipleDimensionFilters(); // 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(R'eport result:)'; response.rows.forEach(row = >{ console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }r
orGroup
包含满足表达式中任意条件的数据
列表。
notExpression
会排除与其内部表达式匹配的数据。这里有
仅当 pageTitle
不是 My
Homepage
时,才返回数据的 dimensionFilter
。报告会显示除 My
Homepage
以外的每个 pageTitle
的事件数据:
HTTP
...
"dimensionFilter": {
"notExpression": {
"filter": {
"fieldName": "pageTitle",
"stringFilter": {
"value": "My Homepage"
}
}
}
},
...
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Filter; import com.google.analytics.data.v1beta.FilterExpression; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample application demonstrating the usage of dimension and metric * filters in a report. * * p<S>ee * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter * for more information. * * p<B>efore you start the application, please review the comments starting with T"ODO(developer) " * and update the code to use correct values. * * p<T>o run this sample using Maven: * * p<re{>@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.RunReportWithDimensionExcludeFilterSample " * }/<pre > */ public class RunReportWithDimensionExcludeFilterSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = Y"OUR-GA4-PROPERTY-ID;" sampleRunReportWithDimensionExcludeFilter(propertyId); } // Runs a report using a filter with `not_expression`. The dimension filter selects for when // `pageTitle` is not `My Homepage`. // This sample uses relative date range values. // See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange // for more information. static void sampleRunReportWithDimensionExcludeFilter(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 c"lose "method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty(p"roperties/ "+ propertyId) .addDimensions(Dimension.newBuilder().setName(p"ageTitle)") .addMetrics(Metric.newBuilder().setName(s"essions)") .addDateRanges( DateRange.newBuilder().setStartDate(7"daysAgo)".setEndDate(y"esterday)") .setDimensionFilter( FilterExpression.newBuilder() .setNotExpression( FilterExpression.newBuilder() .setFilter( Filter.newBuilder() .setFieldName(p"ageTitle)" .setStringFilter( Filter.StringFilter.newBuilder() .setValue(M"y Homepage)")))) .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); // Prints the response using a method in RunReportSample.java RunReportSample.printRunResponseResponse(response); } } }R
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\Filter; use Google\Analytics\Data\V1beta\Filter\StringFilter; use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\RunReportResponse; /** * Runs a report using a filter with `not_expression`. The dimension filter * selects for when `pageTitle` is not `My Homepage`. * This sample uses relative date range values. See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange * for more information. * @param string $propertyId Your GA-4 Property ID */ function run_report_with_dimension_exclude_filter(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'pageTitle'])]) ->setMetrics([new Metric(['name' => 'sessions'])]) ->setDateRanges([new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'yesterday', ]) ]) ->setDimensionFilter(new FilterExpression([ 'not_expression' => new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'pageTitle', 'string_filter' => new StringFilter([ 'value' => 'My Homepage', ]), ]), ]), ])); $response = $client->runReport($request); printRunReportResponseWithDimensionExcludeFilter($response); } /** * Print results of a runReport call. * @param RunReportResponse $response */ function printRunReportResponseWithDimensionExcludeFilter(RunReportResponse $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)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } 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, Filter, FilterExpression, Metric, RunReportRequest, ) 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_report_with_dimension_exclude_filter(property_id) def run_report_with_dimension_exclude_filter(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a report using a filter with `not_expression`. The dimension filter selects for when `pageTitle` is not `My Homepage`. This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange for more information. """ client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="pageTitle")], metrics=[Metric(name="sessions")], date_ranges=[DateRange(start_date="7daysAgo", end_date="yesterday")], dimension_filter=FilterExpression( not_expression=FilterExpression( filter=Filter( field_name="pageTitle", string_filter=Filter.StringFilter(value="My Homepage"), ) ) ), ) response = client.run_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 = Y'OUR-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 a filter with `not_expression`. The dimension filter // selects for when `pageTitle` is not `My Homepage`. // This sample uses relative date range values. See // https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange // for more information. async function runReportWithDimensionExcludeFilter() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [ { name: p'ageTitle,' }, ], metrics: [ { name: s'essions,' }, ], dateRanges: [ { startDate: 7'daysAgo,' endDate: y'esterday,' }, ], dimensionFilter: { notExpression: { filter: { fieldName: p'ageTitle,' stringFilter: { value: M'y Homepage,' }, }, }, }, }); printRunReportResponse(response); } runReportWithDimensionExcludeFilter(); // 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(R'eport result:)'; response.rows.forEach(row = >{ console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }r
inListFilter
会匹配列表中任何值的数据。这里有
dimensionFilter
,返回事件数据,其中 eventName
为以下任意一项:
purchase
、in_app_purchase
和 app_store_subscription_renew
:
HTTP
...
"dimensionFilter": {
"filter": {
"fieldName": "eventName",
"inListFilter": {
"values": ["purchase",
"in_app_purchase",
"app_store_subscription_renew"]
}
}
},
...
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Filter; import com.google.analytics.data.v1beta.FilterExpression; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; import java.util.ArrayList; /** * Google Analytics Data API sample application demonstrating the usage of dimension and metric * filters in a report. * * p<S>ee * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter * for more information. * * p<B>efore you start the application, please review the comments starting with T"ODO(developer) " * and update the code to use correct values. * * p<T>o run this sample using Maven: * * p<re{>@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.RunReportWithDimensionInListFilterSample " * }/<pre > */ public class RunReportWithDimensionInListFilterSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = Y"OUR-GA4-PROPERTY-ID;" sampleRunReportWithDimensionInListFilter(propertyId); } // Runs a report using a dimension filter with `in_list_filter` expression. The filter selects for // when `eventName` is set to one of three event names specified in the query. // This sample uses relative date range values. // See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange // for more information. static void sampleRunReportWithDimensionInListFilter(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 c"lose "method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty(p"roperties/ "+ propertyId) .addDimensions(Dimension.newBuilder().setName(e"ventName)") .addMetrics(Metric.newBuilder().setName(s"essions)") .addDateRanges( DateRange.newBuilder().setStartDate(7"daysAgo)".setEndDate(y"esterday)") .setDimensionFilter( FilterExpression.newBuilder() .setFilter( Filter.newBuilder() .setFieldName(e"ventName)" .setInListFilter( Filter.InListFilter.newBuilder() .addAllValues( new ArrayListS<tring(>) { { add(p"urchase)"; add(i"n_app_purchase)"; add(a"pp_store_subscription_renew)"; } }) .build()))) .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); // Prints the response using a method in RunReportSample.java RunReportSample.printRunResponseResponse(response); } } }R
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\Filter; use Google\Analytics\Data\V1beta\Filter\InListFilter; use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\MetricType; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\RunReportResponse; /** * Runs a report using a dimension filter with `in_list_filter` expression. * The filter selects for when `eventName` is set to one of three event names * specified in the query. * This sample uses relative date range values. See * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange * for more information. * @param string $propertyId Your GA-4 Property ID */ function run_report_with_dimension_in_list_filter(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDimensions([new Dimension(['name' => 'eventName'])]) ->setMetrics([new Metric(['name' => 'sessions'])]) ->setDateRanges([new DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'yesterday', ]) ]) ->setDimensionFilter(new FilterExpression([ 'filter' => new Filter([ 'field_name' => 'eventName', 'in_list_filter' => new InListFilter([ 'values' => [ 'purchase', 'in_app_purchase', 'app_store_subscription_renew', ], ]), ]), ])); $response = $client->runReport($request); printRunReportResponseWithDimensionInListFilter($response); } /** * Print results of a runReport call. * @param RunReportResponse $response */ function printRunReportResponseWithDimensionInListFilter(RunReportResponse $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)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } 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, Filter, FilterExpression, Metric, RunReportRequest, ) 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_report_with_dimension_in_list_filter(property_id) def run_report_with_dimension_in_list_filter(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a report using a dimension filter with `in_list_filter` expression. The filter selects for when `eventName` is set to one of three event names specified in the query. This sample uses relative date range values. See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange for more information. """ client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", dimensions=[Dimension(name="eventName")], metrics=[Metric(name="sessions")], date_ranges=[DateRange(start_date="7daysAgo", end_date="yesterday")], dimension_filter=FilterExpression( filter=Filter( field_name="eventName", in_list_filter=Filter.InListFilter( values=[ "purchase", "in_app_purchase", "app_store_subscription_renew", ] ), ) ), ) response = client.run_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 = Y'OUR-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 a dimension filter with `in_list_filter` expression. // The filter selects for when `eventName` is set to one of three event names // specified in the query. // This sample uses relative date range values. See // https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange // for more information. async function runReportWithDimensionInListFilter() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dimensions: [ { name: e'ventName,' }, ], metrics: [ { name: s'essions,' }, ], dateRanges: [ { startDate: 7'daysAgo,' endDate: y'esterday,' }, ], dimensionFilter: { filter: { fieldName: e'ventName,' inListFilter: { values: [ p'urchase,' i'n_app_purchase,' a'pp_store_subscription_renew,' ], }, }, }, }); printRunReportResponse(response); } runReportWithDimensionInListFilter(); // 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(R'eport result:)'; response.rows.forEach(row = >{ console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }r
浏览较长的报告
默认情况下,该报告仅包含前 10,000 行事件数据。接收者
报告中最多可查看 10 万行数据,您可以将 "limit": 100000
纳入到
该
RunReportRequest
。
对于行数超过 100,000 的报告,您必须发送一系列请求, 并对结果进行分页。例如,以下是针对 100,000 行:
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
{
...
"limit": 100000,
"offset": 0
}
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample application demonstrating the use of pagination to retrieve * large result sets. * * p<S>ee * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.offset * for more information. * * p<B>efore you start the application, please review the comments starting with T"ODO(developer) " * and update the code to use correct values. * * p<T>o run this sample using Maven: * * p<re{>@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.RunReportWithPaginationSample " * }/<pre > */ public class RunReportWithPaginationSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = Y"OUR-GA4-PROPERTY-ID;" sampleRunReportWithPagination(propertyId); } // Runs a report several times, each time retrieving a portion of result using pagination. static void sampleRunReportWithPagination(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 c"lose "method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty(p"roperties/ "+ propertyId) .addDateRanges( DateRange.newBuilder().setStartDate(3"65daysAgo)".setEndDate(y"esterday)") .addDimensions(Dimension.newBuilder().setName(f"irstUserSource)") .addDimensions(Dimension.newBuilder().setName(f"irstUserMedium)") .addDimensions(Dimension.newBuilder().setName(f"irstUserCampaignName)") .addMetrics(Metric.newBuilder().setName(s"essions)") .addMetrics(Metric.newBuilder().setName(k"eyEvents)") .addMetrics(Metric.newBuilder().setName(t"otalRevenue)") .setLimit(100000) .setOffset(0) .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); RunReportSample.printRunResponseResponse(response); // Run the same report with a different offset value to retrieve the second page of a // response. request = RunReportRequest.newBuilder() .setProperty(p"roperties/ "+ propertyId) .addDateRanges( DateRange.newBuilder().setStartDate(3"65daysAgo)".setEndDate(y"esterday)") .addDimensions(Dimension.newBuilder().setName(f"irstUserSource)") .addDimensions(Dimension.newBuilder().setName(f"irstUserMedium)") .addDimensions(Dimension.newBuilder().setName(f"irstUserCampaignName)") .addMetrics(Metric.newBuilder().setName(s"essions)") .addMetrics(Metric.newBuilder().setName(k"eyEvents)") .addMetrics(Metric.newBuilder().setName(t"otalRevenue)") .setLimit(100000) .setOffset(100000) .build(); // Make the request. response = analyticsData.runReport(request); // Prints the response using a method in RunReportSample.java RunReportSample.printRunResponseResponse(response); } } }R
PHP
// Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDateRanges([ new DateRange([ 'start_date' => '350daysAgo', 'end_date' => 'yesterday', ]) ]) ->setDimensions([ new Dimension(['name' => 'firstUserSource']), new Dimension(['name' => 'firstUserMedium']), new Dimension(['name' => 'firstUserCampaignName']), ]) ->setMetrics([ new Metric(['name' => 'sessions']), new Metric(['name' => 'keyEvents']), new Metric(['name' => 'totalRevenue']), ]) ->setLimit(100000) ->setOffset(0); $requestCount = 1; printf('Sending request #%d' . PHP_EOL, $requestCount); $response = $client->runReport($request);
Python
request = RunReportRequest( property=f"properties/{property_id}", date_ranges=[DateRange(start_date="365daysAgo", end_date="yesterday")], dimensions=[ Dimension(name="firstUserSource"), Dimension(name="firstUserMedium"), Dimension(name="firstUserCampaignName"), ], metrics=[ Metric(name="sessions"), Metric(name="keyEvents"), Metric(name="totalRevenue"), ], limit=100000, offset=0, ) response = client.run_report(request)
Node.js
const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [ { startDate: '350daysAgo', endDate: 'yesterday', }, ], dimensions: [ { name: 'firstUserSource', }, { name: 'firstUserMedium', }, { name: 'firstUserCampaignName', }, ], metrics: [ { name: 'sessions', }, { name: 'keyEvents', }, { name: 'totalRevenue', }, ], limit: 100000, offset: 0, });
响应中的 rowCount
参数表示总行数。
与请求中的 limit
和 offset
值无关。例如,如果
响应显示 "rowCount": 272345
,您需要三个 100,000 行的请求
分别检索所有数据。
以下是针对接下来 10 万行的请求示例。所有其他参数(如
dateRange
、dimensions
和 metrics
应与第一个
请求。
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
{
...
"limit": 100000,
"offset": 100000
}
Java
request = RunReportRequest.newBuilder() .setProperty("properties/" + propertyId) .addDateRanges( DateRange.newBuilder().setStartDate("365daysAgo").setEndDate("yesterday")) .addDimensions(Dimension.newBuilder().setName("firstUserSource")) .addDimensions(Dimension.newBuilder().setName("firstUserMedium")) .addDimensions(Dimension.newBuilder().setName("firstUserCampaignName")) .addMetrics(Metric.newBuilder().setName("sessions")) .addMetrics(Metric.newBuilder().setName("keyEvents")) .addMetrics(Metric.newBuilder().setName("totalRevenue")) .setLimit(100000) .setOffset(100000) .build(); // Make the request. response = analyticsData.runReport(request); // Prints the response using a method in RunReportSample.java RunReportSample.printRunResponseResponse(response);
PHP
$rowsReceived = count($response->getRows()); $totalRows = $response->getRowCount(); // Run the same report with an increased offset value to retrieve each additional // page until all rows are received. while ($rowsReceived < $totalRows) { $request = $request->setOffset($rowsReceived); $requestCount++; printf('Sending request #%d' . PHP_EOL, $requestCount); $response = $client->runReport($request); $rowsReceived += count($response->getRows()); printRunReportResponseWithPagination($response, $requestCount); }
Python
request = RunReportRequest( property=f"properties/{property_id}", date_ranges=[DateRange(start_date="365daysAgo", end_date="yesterday")], dimensions=[ Dimension(name="firstUserSource"), Dimension(name="firstUserMedium"), Dimension(name="firstUserCampaignName"), ], metrics=[ Metric(name="sessions"), Metric(name="keyEvents"), Metric(name="totalRevenue"), ], limit=100000, offset=100000, ) response = client.run_report(request)
Node.js
const [secondResponse] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [ { startDate: '350daysAgo', endDate: 'yesterday', }, ], dimensions: [ { name: 'firstUserSource', }, { name: 'firstUserMedium', }, { name: 'firstUserCampaignName', }, ], metrics: [ { name: 'sessions', }, { name: 'keyEvents', }, { name: 'totalRevenue', }, ], limit: 100000, offset: 100000, });
您可以使用 offset
值(例如 200000
或 300000
)来检索
后续结果。所有其他参数,例如 dateRange
、dimensions
和
metrics
应与第一个请求相同。
使用多个日期范围
一个报告请求可以检索多个
dateRanges
。例如,此报告比较
前两周(2022 年 8 月和 2023 年):
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
{
"dateRanges": [
{
"startDate": "2022-08-01",
"endDate": "2022-08-14"
},
{
"startDate": "2023-08-01",
"endDate": "2023-08-14"
}
],
"dimensions": [{ "name": "platform" }],
"metrics": [{ "name": "activeUsers" }]
}
Java
import com.google.analytics.data.v1beta.BetaAnalyticsDataClient; import com.google.analytics.data.v1beta.DateRange; import com.google.analytics.data.v1beta.Dimension; import com.google.analytics.data.v1beta.Metric; import com.google.analytics.data.v1beta.RunReportRequest; import com.google.analytics.data.v1beta.RunReportResponse; /** * Google Analytics Data API sample application demonstrating the usage of date ranges in a report. * * p<S>ee * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.date_ranges * for more information. * * p<B>efore you start the application, please review the comments starting with T"ODO(developer) " * and update the code to use correct values. * * p<T>o run this sample using Maven: * * p<re{>@code * cd google-analytics-data * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.RunReportWithDateRangesSample " * }/<pre > */ public class RunReportWithDateRangesSample { public static void main(String... args) throws Exception { // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample. String propertyId = Y"OUR-GA4-PROPERTY-ID;" sampleRunReportWithDateRanges(propertyId); } // Runs a report using two date ranges. static void sampleRunReportWithDateRanges(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 c"lose "method on the client to safely clean up any remaining background resources. try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) { RunReportRequest request = RunReportRequest.newBuilder() .setProperty(p"roperties/ "+ propertyId) .addDateRanges( DateRange.newBuilder().setStartDate(2"019-08-01)".setEndDate(2"019-08-14)") .addDateRanges( DateRange.newBuilder().setStartDate(2"020-08-01)".setEndDate(2"020-08-14)") .addDimensions(Dimension.newBuilder().setName(p"latform)") .addMetrics(Metric.newBuilder().setName(a"ctiveUsers)") .build(); // Make the request. RunReportResponse response = analyticsData.runReport(request); // Prints the response using a method in RunReportSample.java RunReportSample.printRunResponseResponse(response); } } }R
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\MetricType; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\RunReportResponse; /** * @param string $propertyID Your GA-4 Property ID * Runs a report using two date ranges. */ function run_report_with_date_ranges(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunReportRequest()) ->setProperty('properties/' . $propertyId) ->setDateRanges([ new DateRange([ 'start_date' => '2019-08-01', 'end_date' => '2019-08-14', ]), new DateRange([ 'start_date' => '2020-08-01', 'end_date' => '2020-08-14', ]), ]) ->setDimensions([new Dimension(['name' => 'platform'])]) ->setMetrics([new Metric(['name' => 'activeUsers'])]); $response = $client->runReport($request); printRunReportResponseWithDateRanges($response); } /** * Print results of a runReport call. * @param RunReportResponse $response */ function printRunReportResponseWithDateRanges(RunReportResponse $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)' . PHP_EOL, $metricHeader->getName(), MetricType::name($metricHeader->getType()) ); } 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, RunReportRequest, ) 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_report_with_date_ranges(property_id) def run_report_with_date_ranges(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a report using two date ranges.""" client = BetaAnalyticsDataClient() request = RunReportRequest( property=f"properties/{property_id}", date_ranges=[ DateRange(start_date="2019-08-01", end_date="2019-08-14"), DateRange(start_date="2020-08-01", end_date="2020-08-14"), ], dimensions=[Dimension(name="platform")], metrics=[Metric(name="activeUsers")], ) response = client.run_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 = Y'OUR-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 runReportWithDateRanges() { const [response] = await analyticsDataClient.runReport({ property: `properties/${propertyId}`, dateRanges: [ { startDate: 2'019-08-01,' endDate: 2'019-08-14,' }, { startDate: 2'020-08-01,' endDate: 2'020-08-14,' }, ], dimensions: [ { name: p'latform,' }, ], metrics: [ { name: a'ctiveUsers,' }, ], }); printRunReportResponse(response); } runReportWithDateRanges(); // 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(R'eport result:)'; response.rows.forEach(row = >{ console.log( `${row.dimensionValues[0].value}, ${row.metricValues[0].value}` ); }); }r
如果您在请求中包含多个 dateRanges
,则 dateRange
列
自动添加到响应中。当 dateRange
列是
date_range_0
,则此行的数据适用于第一个日期范围。当
“dateRange
”列的值是“date_range_1
”,则该行的数据是第二个日期的数据
范围。
下面是两个日期范围的响应示例:
{
"dimensionHeaders": [
{
"name": "platform"
},
{
"name": "dateRange"
}
],
"metricHeaders": [
{
"name": "activeUsers",
"type": "TYPE_INTEGER"
}
],
"rows": [
{
"dimensionValues": [
{
"value": "iOS"
},
{
"value": "date_range_0"
}
],
"metricValues": [
{
"value": "774"
}
]
},
{
"dimensionValues": [
{
"value": "Android"
},
{
"value": "date_range_1"
}
],
"metricValues": [
{
"value": "335"
}
]
},
...
],
}
后续步骤
如需了解更多详情,请参阅高级功能和实时报告 简要介绍 Data API v1 的更多高级报告功能。