建立即時報表

這是 Google Analytics Data API 第 1 版 Realtime Reporting API 方法的總覽。如需 API 的詳細參考資料,請參閱 API 參考資料

事件傳送到 Google Analytics (分析) 後,就會在即時報表中顯示。即時報表會顯示從現在到 30 分鐘之前的事件和使用資料 (Google Analytics (分析) 360 資源最長 60 分鐘),並可用於應用程式,例如網站訪客的即時計數器。

與 Data API v1 的核心報表功能相比,即時報表僅支援部分維度和指標

與核心報表共用的功能

即時報表要求的語意與許多共用功能的核心報表要求具有相同的語意。舉例來說,分頁維度篩選器使用者屬性在即時報表中的行為與核心報表相同。請熟悉 Data API v1 核心報表功能總覽,因為本文的其餘部分將著重於即時報表要求的專屬功能。

檢舉要求

如要要求即時報表,您可以建構 RunRealtimeReportRequest 物件。建議您先使用以下請求參數:

  • dimensions」欄位中至少有一個有效項目。
  • metrics 欄位中至少有一個有效項目。

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

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_PROPERTY_ID:runRealtimeReport
{
  "dimensions": [{ "name": "country" }],
  "metrics": [{ "name": "activeUsers" }]
}

Java


import com.google.analytics.data.v1beta.BetaAnalyticsDataClient;
import com.google.analytics.data.v1beta.Dimension;
import com.google.analytics.data.v1beta.DimensionHeader;
import com.google.analytics.data.v1beta.Metric;
import com.google.analytics.data.v1beta.MetricHeader;
import com.google.analytics.data.v1beta.Row;
import com.google.analytics.data.v1beta.RunRealtimeReportRequest;
import com.google.analytics.data.v1beta.RunRealtimeReportResponse;

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * <p>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * <p>Before you start the application, please review the comments starting with "TODO(developer)"
 * and update the code to use correct values.
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportSample"
 * }</pre>
 */
public class RunRealtimeReportSample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.
    String propertyId = "YOUR-GA4-PROPERTY-ID";
    sampleRunRealtimeReport(propertyId);
  }

  // Runs a realtime report on a Google Analytics 4 property.
  static void sampleRunRealtimeReport(String propertyId) throws Exception {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunRealtimeReportRequest request =
          RunRealtimeReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("country"))
              .addMetrics(Metric.newBuilder().setName("activeUsers"))
              .build();

      // Make the request.
      RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request);
      printRunRealtimeReportResponse(response);
    }
  }

  // Prints results of a runRealReport call.
  static void printRunRealtimeReportResponse(RunRealtimeReportResponse response) {
    System.out.printf("%s rows received%n", response.getRowsList().size());

    for (DimensionHeader header : response.getDimensionHeadersList()) {
      System.out.printf("Dimension header name: %s%n", header.getName());
    }

    for (MetricHeader header : response.getMetricHeadersList()) {
      System.out.printf("Metric header name: %s (%s)%n", header.getName(), header.getType());
    }

    System.out.println("Report result:");
    for (Row row : response.getRowsList()) {
      System.out.printf(
          "%s, %s%n", row.getDimensionValues(0).getValue(), row.getMetricValues(0).getValue());
    }
  }
}

Python

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    Dimension,
    Metric,
    RunRealtimeReportRequest,
)

from run_report import print_run_report_response


def run_sample():
    """Runs the sample."""
    # TODO(developer): Replace this variable with your Google Analytics 4
    #  property ID before running the sample.
    property_id = "YOUR-GA4-PROPERTY-ID"
    run_realtime_report(property_id)


def run_realtime_report(property_id="YOUR-GA4-PROPERTY-ID"):
    """Runs a realtime report on a Google Analytics 4 property."""
    client = BetaAnalyticsDataClient()

    request = RunRealtimeReportRequest(
        property=f"properties/{property_id}",
        dimensions=[Dimension(name="country")],
        metrics=[Metric(name="activeUsers")],
    )
    response = client.run_realtime_report(request)
    print_run_report_response(response)


報表回應

API 要求的即時報表回應主要是標頭和資料列。標頭包含 DimensionHeadersMetricHeaders,這些資料欄會列出報表中的資料欄。針對報表中的資料欄,每列包含 DimensionValuesMetricValues。在要求、標頭和每一列中,資料欄的順序會保持一致。

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

{
  "dimensionHeaders": [
    {
      "name": "country"
    }
  ],
  "metricHeaders": [
    {
      "name": "activeUsers",
      "type": "TYPE_INTEGER"
    }
  ],
  "rows": [
    {
      "dimensionValues": [
        {
          "value": "Japan"
        }
      ],
      "metricValues": [
        {
          "value": "2541"
        }
      ]
    },
    {
      "dimensionValues": [
        {
          "value": "France"
        }
      ],
      "metricValues": [
        {
          "value": "12"
        }
      ]
    }
  ],
  "rowCount": 2
}

尺寸

「維度」可用來說明網站或應用程式的事件資料,並將資料分組。舉例來說,city 維度會指出每個事件的來源城市 (「巴黎」或「紐約」)。在報表要求中,您可以指定零個或多個維度。如需即時要求中可用的 API 維度名稱完整清單,請參閱「即時維度」。

舉例來說,這項要求會將「活躍使用者」歸為兩個維度欄:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/property/GA4_PROPERTY_ID:runRealtimeReport
  {
    "dimensions": [
      {
        "name": "country"
      },
      {
        "name": "city"
      }
    ],
    "metrics": [{ "name": "activeUsers" }]
  }

Java


import com.google.analytics.data.v1beta.BetaAnalyticsDataClient;
import com.google.analytics.data.v1beta.Dimension;
import com.google.analytics.data.v1beta.Metric;
import com.google.analytics.data.v1beta.RunRealtimeReportRequest;
import com.google.analytics.data.v1beta.RunRealtimeReportResponse;

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * <p>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * <p>Before you start the application, please review the comments starting with "TODO(developer)"
 * and update the code to use correct values.
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportWithMultipleDimensionsSample"
 * }</pre>
 */
public class RunRealtimeReportWithMultipleDimensionsSample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.
    String propertyId = "YOUR-GA4-PROPERTY-ID";
    sampleRunRealtimeReportWithMultipleDimensions(propertyId);
  }

  // Runs a realtime report on a Google Analytics 4 property.
  static void sampleRunRealtimeReportWithMultipleDimensions(String propertyId) throws Exception {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunRealtimeReportRequest request =
          RunRealtimeReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("country"))
              .addDimensions(Dimension.newBuilder().setName(("city")))
              .addMetrics(Metric.newBuilder().setName("activeUsers"))
              .build();

      // Make the request.
      RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request);
      // Prints the response using a method in RunRealtimeReportSample.java
      RunRealtimeReportSample.printRunRealtimeReportResponse(response);
    }
  }
}

Python

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    Dimension,
    Metric,
    RunRealtimeReportRequest,
)

from run_report import print_run_report_response


def run_sample():
    """Runs the sample."""
    # TODO(developer): Replace this variable with your Google Analytics 4
    #  property ID before running the sample.
    property_id = "YOUR-GA4-PROPERTY-ID"
    run_realtime_report_with_multiple_dimensions(property_id)


def run_realtime_report_with_multiple_dimensions(property_id="YOUR-GA4-PROPERTY-ID"):
    """Runs a realtime report on a Google Analytics 4 property."""
    client = BetaAnalyticsDataClient()

    request = RunRealtimeReportRequest(
        property=f"properties/{property_id}",
        dimensions=[Dimension(name="country"), Dimension(name="city")],
        metrics=[Metric(name="activeUsers")],
    )
    response = client.run_realtime_report(request)
    print_run_report_response(response)


舉例來說,報表回應中的一列可能包含以下內容。這個資料列代表您的網站或應用程式在過去 30 分鐘內有 47 位活躍使用者,而且事件來自南非開普敦。

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

指標

指標是網站或應用程式事件資料的量化評估項目。在報表要求中,您可以指定一或多個指標。如需要求中可用的 API 指標名稱完整清單,請參閱即時指標

舉例來說,此要求會顯示兩個按維度 unifiedScreenName 分組的指標:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/property/GA4_PROPERTY_ID:runRealtimeReport
  {
    "dimensions": [{ "name": "unifiedScreenName" }],
    "metrics": [
      {
        "name": "screenPageViews"
      },
      {
        "name": "conversions"
      }
    ],
  }

Java


import com.google.analytics.data.v1beta.BetaAnalyticsDataClient;
import com.google.analytics.data.v1beta.Dimension;
import com.google.analytics.data.v1beta.Metric;
import com.google.analytics.data.v1beta.RunRealtimeReportRequest;
import com.google.analytics.data.v1beta.RunRealtimeReportResponse;

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * <p>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * <p>Before you start the application, please review the comments starting with "TODO(developer)"
 * and update the code to use correct values.
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportWithMultipleMetricsSample"
 * }</pre>
 */
public class RunRealtimeReportWithMultipleMetricsSample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.
    String propertyId = "YOUR-GA4-PROPERTY-ID";
    sampleRunRealtimeReportWithMultipleMetrics(propertyId);
  }

  // Runs a realtime report on a Google Analytics 4 property.
  static void sampleRunRealtimeReportWithMultipleMetrics(String propertyId) throws Exception {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunRealtimeReportRequest request =
          RunRealtimeReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDimensions(Dimension.newBuilder().setName("unifiedScreenName"))
              .addMetrics(Metric.newBuilder().setName(("screenPageViews")))
              .addMetrics(Metric.newBuilder().setName("conversions"))
              .build();

      // Make the request.
      RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request);
      // Prints the response using a method in RunRealtimeReportSample.java
      RunRealtimeReportSample.printRunRealtimeReportResponse(response);
    }
  }
}

Python

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    Dimension,
    Metric,
    RunRealtimeReportRequest,
)

from run_report import print_run_report_response


def run_sample():
    """Runs the sample."""
    # TODO(developer): Replace this variable with your Google Analytics 4
    #  property ID before running the sample.
    property_id = "YOUR-GA4-PROPERTY-ID"
    run_realtime_report_with_multiple_metrics(property_id)


def run_realtime_report_with_multiple_metrics(property_id="YOUR-GA4-PROPERTY-ID"):
    """Runs a realtime report on a Google Analytics 4 property."""
    client = BetaAnalyticsDataClient()

    request = RunRealtimeReportRequest(
        property=f"properties/{property_id}",
        dimensions=[Dimension(name="unifiedScreenName")],
        metrics=[Metric(name="screenPageViews"), Metric(name="conversions")],
    )
    response = client.run_realtime_report(request)
    print_run_report_response(response)


舉例來說,報表回應中的一列可能包含以下內容。這一列代表 main_menu 的網頁標題 (網站) 或畫面名稱 (應用程式) 在過去 30 分鐘內獲得 257 次瀏覽和 72 個轉換事件。

"rows": [
...
{
  "dimensionValues": [
    {
      "value": "main_menu"
    }
  ],
  "metricValues": [
    {
      "value": "257"
    },
    {
      "value": "72"
    }
  ]
},
...
],

分鐘範圍

在即時報表要求中,您可以使用 minuteRanges 欄位,指定要讀取的事件資料的「Minute Ranges」。查詢中最多可使用兩個不同的分鐘範圍。如果查詢中沒有分鐘範圍規格,則會使用過去 30 分鐘的每分鐘範圍。

例如,下方的要求會顯示兩個不同分鐘範圍的活躍使用者計數:

  • 範圍 #1:從 4 分鐘前開始,直到現在為止。
  • 範圍 #2:從 29 分鐘前開始,直到 25 分鐘前 (含首尾)。

HTTP

POST https://analyticsdata.googleapis.com/v1beta/property/GA4_PROPERTY_ID:runRealtimeReport
  {
    "metrics": [
      {
        "name": "activeUsers"
      }
    ],
    "minuteRanges": [
      {
        "name": "0-4 minutes ago",
        "startMinutesAgo": 4,
      },
      {
        "name": "25-29 minutes ago",
        "startMinutesAgo": 29,
        "endMinutesAgo": 25,
      }
    ],
  }

Java


import com.google.analytics.data.v1beta.BetaAnalyticsDataClient;
import com.google.analytics.data.v1beta.Metric;
import com.google.analytics.data.v1beta.MinuteRange;
import com.google.analytics.data.v1beta.RunRealtimeReportRequest;
import com.google.analytics.data.v1beta.RunRealtimeReportResponse;

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * <p>See
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * <p>Before you start the application, please review the comments starting with "TODO(developer)"
 * and update the code to use correct values.
 *
 * <p>To run this sample using Maven:
 *
 * <pre>{@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass="com.google.analytics.data.samples.RunRealtimeReportWithMinuteRangesSample"
 * }</pre>
 */
public class RunRealtimeReportWithMinuteRangesSample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace with your Google Analytics 4 property ID before running the sample.
    String propertyId = "YOUR-GA4-PROPERTY-ID";
    sampleRunRealtimeReportWithMinuteRanges(propertyId);
  }

  // Runs a realtime report on a Google Analytics 4 property.
  static void sampleRunRealtimeReportWithMinuteRanges(String propertyId) throws Exception {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunRealtimeReportRequest request =
          RunRealtimeReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addMetrics(Metric.newBuilder().setName(("activeUsers")))
              .addMinuteRanges(
                  MinuteRange.newBuilder().setName("0-4 minutes ago").setStartMinutesAgo(4))
              .addMinuteRanges(
                  MinuteRange.newBuilder()
                      .setName("25-29 minutes ago")
                      .setEndMinutesAgo(29)
                      .setEndMinutesAgo(25))
              .build();

      // Make the request.
      RunRealtimeReportResponse response = analyticsData.runRealtimeReport(request);
      // Prints the response using a method in RunRealtimeReportSample.java
      RunRealtimeReportSample.printRunRealtimeReportResponse(response);
    }
  }
}

Python

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    Metric,
    MinuteRange,
    RunRealtimeReportRequest,
)

from run_report import print_run_report_response


def run_sample():
    """Runs the sample."""
    # TODO(developer): Replace this variable with your Google Analytics 4
    #  property ID before running the sample.
    property_id = "YOUR-GA4-PROPERTY-ID"
    run_realtime_report_with_minute_ranges(property_id)


def run_realtime_report_with_minute_ranges(property_id="YOUR-GA4-PROPERTY-ID"):
    """Runs a realtime report on a Google Analytics 4 property. Dimensions
    field is omitted in the query, which results in total values of active users
    returned for each minute range in the report.

    Note the `dateRange` dimension added to the report response automatically
    as a result of querying multiple minute ranges.
    """
    client = BetaAnalyticsDataClient()

    request = RunRealtimeReportRequest(
        property=f"properties/{property_id}",
        metrics=[Metric(name="activeUsers")],
        minute_ranges=[
            MinuteRange(name="0-4 minutes ago", start_minutes_ago=4),
            MinuteRange(
                name="25-29 minutes ago", start_minutes_ago=29, end_minutes_ago=25
            ),
        ],
    )
    response = client.run_realtime_report(request)
    print_run_report_response(response)


以下是查詢的完整範例回應。請注意,由於查詢多個分鐘的範圍,系統會自動將 dateRange 維度新增至報表回應。

  {
    "dimensionHeaders": [
      {
        "name": "dateRange"
      }
    ],
    "metricHeaders": [
      {
        "name": "activeUsers",
        "type": "TYPE_INTEGER"
      }
    ],
    "rows": [
      {
        "dimensionValues": [
          {
            "value": "0-4 minutes ago"
          }
        ],
        "metricValues": [
          {
            "value": "16"
          }
        ]
      },
      {
        "dimensionValues": [
          {
            "value": "25-29 minutes ago"
          }
        ],
        "metricValues": [
          {
            "value": "14"
          }
        ]
      }
    ],
    "rowCount": 2,
    "kind": "analyticsData#runRealtimeReport"
  }