建立報表

本指南說明如何使用 Google Analytics Data API v1,為 Analytics (分析) 資料建立基本報表。Google Data API 第 1 版的報表與 Google Analytics (分析) UI 的「報表」部分中產生的報表類似。

本指南說明核心報表,即 Data API 的一般報表功能。Data API v1 也提供專用的即時報表漏斗報表

我們建議您使用 runReport 查詢方法,本指南的所有範例都使用此方法。如需其他核心回報方法的總覽,請參閱進階功能。使用查詢探索工具測試查詢。

Reports overview

報表Google Analytics (分析) 4 資源事件資料的表格。每份報表表格都會包含查詢中要求的維度和指標,資料則位於個別資料列中。

使用篩選器即可只傳回符合特定條件的資料列,請使用分頁來瀏覽結果。

以下報表表格範例會顯示一個維度 (Country) 和指標 (activeUsers):

國家/地區 活躍使用者人數
日本 2541
法國 12

指定資料來源

每個 runReport 要求都必須指定 Google Analytics (分析) 4 資源 ID。您指定的 Analytics (分析) 資源將做為該查詢的資料集使用。範例如下:

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_PROPERTY_ID:runReport

這項要求的回應僅包含您指定為 GA4_PROPERTY_ID 的 Analytics (分析) 資源資料。

如果您使用 Data API 用戶端程式庫,請以 properties/GA4_PROPERTY_ID 格式在 property 參數中指定資料來源。如需使用用戶端程式庫的範例,請參閱快速入門指南

若要在報表中加入 Measurement Protocol 事件,請參閱「將 Measurement Protocol 事件傳送至 Google Analytics (分析)」一文。

產生報表

如要產生報表,請建構 RunReportRequest 物件。建議您從下列參數著手:

  • dateRanges欄位中的有效項目。
  • 在「dimensions」欄位中至少包含一個有效項目。
  • 在「metrics欄位中,至少有一個有效項目。

以下是含建議欄位的要求範例:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_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 = '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 of active users grouped by country.
  async function runReport() {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${propertyId}`,
      dimensions: [
        {
          name: 'country',
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
      dateRanges: [
        {
          startDate: '2020-09-01',
          endDate: '2020-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('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

  runReport();

查詢指標

Metrics 是事件資料的量化測量結果。您必須在 runReport 要求中指定至少一個指標。

如需可供查詢的完整指標清單,請參閱 API 指標

下方要求範例包含三個依維度 date「分組」的指標:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_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>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.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 = "YOUR-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 "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunReportRequest request =
          RunReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("date"))
              .addMetrics(Metric.newBuilder().setName("activeUsers"))
              .addMetrics(Metric.newBuilder().setName("newUsers"))
              .addMetrics(Metric.newBuilder().setName("totalRevenue"))
              .addDateRanges(DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("today"))
              .build();

      // Make the request.
      RunReportResponse response = analyticsData.runReport(request);
      // Prints the response using a method in RunReportSample.java
      RunReportSample.printRunResponseResponse(response);
    }
  }
}

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 = '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 of active users grouped by three metrics.
  async function runReportWithMultipleMetrics() {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${propertyId}`,
      dimensions: [
        {
          name: 'date',
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
        {
          name: 'newUsers',
        },
        {
          name: 'totalRevenue',
        },
      ],
      dateRanges: [
        {
          startDate: '7daysAgo',
          endDate: 'today',
        },
      ],
    });
    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('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

以下範例回應顯示,在 20231025 (2023 年 10 月 25 日) 當天,以 Analytics (分析) 資源幣別計算的 1135 位活躍使用者、512 位新使用者,以及 73.0841 總收益。

"rows": [
...
{
  "dimensionValues": [
    {
      "value": "20231025"
    }
  ],
  "metricValues": [
    {
      "value": "1135"
    },
    {
      "value": "512"
    },
    {
      "value": "73.0841"
    }
  ]
},
...
],

閱讀回覆

報表回應包含資料標頭和資料列。標頭由 DimensionHeadersMetricHeaders 組成,後者會列出報表中的資料欄。每一列都是由 DimensionValuesMetricValues 組成。資料欄在要求、標頭與資料列中的順序會保持一致。

以下是上一個範例要求的回應範例:

{
  "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 維度會指出每個事件的來源城市 (例如 ParisNew York)。runReport 要求的維度是選用項目,每項要求最多可以使用 9 個維度。

如需可用於分組及篩選資料的各項維度清單,請參閱「API 維度」。

群組

以下範例要求將活躍使用者分為三個維度:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_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>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.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 = "YOUR-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 "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunReportRequest request =
          RunReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("country"))
              .addDimensions(Dimension.newBuilder().setName("region"))
              .addDimensions(Dimension.newBuilder().setName("city"))
              .addMetrics(Metric.newBuilder().setName("activeUsers"))
              .addDateRanges(DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("today"))
              .build();

      // Make the request.
      RunReportResponse response = analyticsData.runReport(request);
      // Prints the response using a method in RunReportSample.java
      RunReportSample.printRunResponseResponse(response);
    }
  }
}

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 = '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 of active users grouped by three dimensions.
  async function runReportWithMultipleDimensions() {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${propertyId}`,
      dimensions: [
        {
          name: 'country',
        },
        {
          name: 'region',
        },
        {
          name: 'city',
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
      dateRanges: [
        {
          startDate: '7daysAgo',
          endDate: 'today',
        },
      ],
    });
    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('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

以下是先前要求的報表資料列範例。這一列顯示在指定日期範圍內,有 47 名活躍使用者來自南非開普敦。

"rows": [
...
{
  "dimensionValues": [
    {
      "value": "South Africa"
    },
    {
      "value": "Western Cape"
    },
    {
      "value": "Cape Town"
    }
  ],
  "metricValues": [
    {
      "value": "47"
    }
  ]
},
...
],

篩選器

只會產生特定維度值的資料報表。如要篩選維度,請在 dimensionFilter 欄位中指定 FilterExpression

以下範例會傳回 eventCount 的時間序列報表,而每個 dateeventNamefirst_open 時:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_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>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter
 * 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.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 = "YOUR-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 "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunReportRequest request =
          RunReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("date"))
              .addMetrics(Metric.newBuilder().setName("eventCount"))
              .addDateRanges(
                  DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("yesterday"))
              .setDimensionFilter(
                  FilterExpression.newBuilder()
                      .setFilter(
                          Filter.newBuilder()
                              .setFieldName("eventName")
                              .setStringFilter(
                                  Filter.StringFilter.newBuilder().setValue("first_open"))))
              .build();

      // Make the request.
      RunReportResponse response = analyticsData.runReport(request);
      // Prints the response using a method in RunReportSample.java
      RunReportSample.printRunResponseResponse(response);
    }
  }
}

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 = '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 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: 'date',
        },
      ],
      metrics: [
        {
          name: 'eventCount',
        },
      ],
      dateRanges: [
        {
          startDate: '7daysAgo',
          endDate: 'yesterday',
        },
      ],
      dimensionFilter: {
        filter: {
          fieldName: 'eventName',
          stringFilter: {
            value: 'first_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('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

以下是另一個 FilterExpression 範例,其中 andGroup 僅包含符合運算式清單中所有條件的資料。當 browser 都是 ChromecountryIdUS 時,此 dimensionFilter 會選取:

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>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter
 * 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.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 = "YOUR-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 "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunReportRequest request =
          RunReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("browser"))
              .addMetrics(Metric.newBuilder().setName("activeUsers"))
              .addDateRanges(
                  DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("yesterday"))
              .setDimensionFilter(
                  FilterExpression.newBuilder()
                      .setAndGroup(
                          FilterExpressionList.newBuilder()
                              .addExpressions(
                                  FilterExpression.newBuilder()
                                      .setFilter(
                                          Filter.newBuilder()
                                              .setFieldName("browser")
                                              .setStringFilter(
                                                  Filter.StringFilter.newBuilder()
                                                      .setValue("Chrome"))))
                              .addExpressions(
                                  FilterExpression.newBuilder()
                                      .setFilter(
                                          Filter.newBuilder()
                                              .setFieldName("countryId")
                                              .setStringFilter(
                                                  Filter.StringFilter.newBuilder()
                                                      .setValue("US"))))))
              .build();

      // Make the request.
      RunReportResponse response = analyticsData.runReport(request);
      // Prints the response using a method in RunReportSample.java
      RunReportSample.printRunResponseResponse(response);
    }
  }
}

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 = '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 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: 'browser',
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
      dateRanges: [
        {
          startDate: '7daysAgo',
          endDate: 'yesterday',
        },
      ],
      dimensionFilter: {
        andGroup: {
          expressions: [
            {
              filter: {
                fieldName: 'browser',
                stringFilter: {
                  value: 'Chrome',
                },
              },
            },
            {
              filter: {
                fieldName: 'countryId',
                stringFilter: {
                  value: 'US',
                },
              },
            },
          ],
        },
      },
    });
    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('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

orGroup 包含符合運算式清單中任一條件的資料。

notExpression 會排除與內部運算式相符的資料。以下範例中的dimensionFilter只會在 pageTitle 不是 My Homepage 時傳回資料。此報表會顯示 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>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter
 * 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.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 = "YOUR-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 "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunReportRequest request =
          RunReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("pageTitle"))
              .addMetrics(Metric.newBuilder().setName("sessions"))
              .addDateRanges(
                  DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("yesterday"))
              .setDimensionFilter(
                  FilterExpression.newBuilder()
                      .setNotExpression(
                          FilterExpression.newBuilder()
                              .setFilter(
                                  Filter.newBuilder()
                                      .setFieldName("pageTitle")
                                      .setStringFilter(
                                          Filter.StringFilter.newBuilder()
                                              .setValue("My Homepage")))))
              .build();

      // Make the request.
      RunReportResponse response = analyticsData.runReport(request);
      // Prints the response using a method in RunReportSample.java
      RunReportSample.printRunResponseResponse(response);
    }
  }
}

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 = '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 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: 'pageTitle',
        },
      ],
      metrics: [
        {
          name: 'sessions',
        },
      ],
      dateRanges: [
        {
          startDate: '7daysAgo',
          endDate: 'yesterday',
        },
      ],
      dimensionFilter: {
        notExpression: {
          filter: {
            fieldName: 'pageTitle',
            stringFilter: {
              value: 'My 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('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

inListFilter 會比對清單中任何值的資料。以下 dimensionFilter 會傳回事件資料,其中 eventNamepurchasein_app_purchaseapp_store_subscription_renew 中的任何 purchase

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>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter
 * 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.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 = "YOUR-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 "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunReportRequest request =
          RunReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("eventName"))
              .addMetrics(Metric.newBuilder().setName("sessions"))
              .addDateRanges(
                  DateRange.newBuilder().setStartDate("7daysAgo").setEndDate("yesterday"))
              .setDimensionFilter(
                  FilterExpression.newBuilder()
                      .setFilter(
                          Filter.newBuilder()
                              .setFieldName("eventName")
                              .setInListFilter(
                                  Filter.InListFilter.newBuilder()
                                      .addAllValues(
                                          new ArrayList<String>() {
                                            {
                                              add("purchase");
                                              add("in_app_purchase");
                                              add("app_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);
    }
  }
}

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 = '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 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: 'eventName',
        },
      ],
      metrics: [
        {
          name: 'sessions',
        },
      ],
      dateRanges: [
        {
          startDate: '7daysAgo',
          endDate: 'yesterday',
        },
      ],
      dimensionFilter: {
        filter: {
          fieldName: 'eventName',
          inListFilter: {
            values: [
              'purchase',
              'in_app_purchase',
              'app_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('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

瀏覽長版報表

根據預設,報表只包含前 10,000 列的事件資料。如要在報表中查看最多 100,000 列資料,您可以在 RunReportRequest 中加入 "limit": 100000

如果報表的資料列超過 100,000 列,您就必須傳送一系列要求,並逐頁查看結果。例如,以下是前 100,000 個資料列的要求:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_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>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.offset
 * 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.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 = "YOUR-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 "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunReportRequest 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("conversions"))
              .addMetrics(Metric.newBuilder().setName("totalRevenue"))
              .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("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("conversions"))
              .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

    // 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' => 'conversions']),
            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="conversions"),
            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: 'conversions',
        },
        {
          name: 'totalRevenue',
        },
      ],
      limit: 100000,
      offset: 0,
    });

回應中的 rowCount 參數代表資料列總數,與要求中的 limitoffset 值無關。舉例來說,如果回應顯示 "rowCount": 272345,您需要 3 個要求 (每個要求 100,000 個),才能擷取所有資料。

以下是接下來 100,000 列的要求範例。所有其他參數 (例如 dateRangedimensionsmetrics) 應與第一個要求相同。

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_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("conversions"))
              .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="conversions"),
            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: 'conversions',
        },
        {
          name: 'totalRevenue',
        },
      ],
      limit: 100000,
      offset: 100000,
    });

您可以使用 offset 值 (例如 200000300000) 擷取後續結果。所有其他參數 (例如 dateRangedimensionsmetrics) 都應與第一個要求相同。

使用多個日期範圍

一個報表要求可擷取多個 dateRanges 的資料。舉例來說,這份報表會比較 2022 年和 2023 年 8 月的前兩週:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_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>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.date_ranges
 * 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.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 = "YOUR-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 "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunReportRequest request =
          RunReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDateRanges(
                  DateRange.newBuilder().setStartDate("2019-08-01").setEndDate("2019-08-14"))
              .addDateRanges(
                  DateRange.newBuilder().setStartDate("2020-08-01").setEndDate("2020-08-14"))
              .addDimensions(Dimension.newBuilder().setName("platform"))
              .addMetrics(Metric.newBuilder().setName("activeUsers"))
              .build();

      // Make the request.
      RunReportResponse response = analyticsData.runReport(request);
      // Prints the response using a method in RunReportSample.java
      RunReportSample.printRunResponseResponse(response);
    }
  }
}

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 = '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 runReportWithDateRanges() {
    const [response] = await analyticsDataClient.runReport({
      property: `properties/${propertyId}`,
      dateRanges: [
        {
          startDate: '2019-08-01',
          endDate: '2019-08-14',
        },
        {
          startDate: '2020-08-01',
          endDate: '2020-08-14',
        },
      ],
      dimensions: [
        {
          name: 'platform',
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
    });
    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('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

在要求中加入多個 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 的其他進階報表功能。