실시간 보고서 만들기

다음은 Realtime Reporting API 메서드의 기능에 대한 개요입니다. 자세히 알아보겠습니다 API에 대한 자세한 내용은 API 참조

이벤트 Google에 전송되고 몇 초 후에 실시간 보고서에 표시됩니다. 분석 실시간 보고서에는 특정 기간의 이벤트 및 사용 데이터가 표시됩니다. 현재 순간부터 30분 전 (Google의 경우 최대 60분)까지 애널리틱스 360 속성)에 사용할 수 있으며, 실시간 스트리밍과 같은 애플리케이션에 웹사이트 방문자 카운터

실시간 보고서는 측정기준 및 측정항목의 제한된 하위 집합을 지원합니다. 를 Data API v1의 핵심 보고서 기능과 비교합니다.

핵심 보고서와 공유 기능

실시간 보고서 요청은 다음의 핵심 보고서 요청과 의미가 동일합니다. 많은 공유 기능을 제공합니다 예: 페이지로 나누기, 측정기준 필터 사용자 속성은 동일하고 실시간 보고서에 핵심 보고서로 표시됩니다. 다음 내용을 숙지하시기 바랍니다. Data API v1의 핵심 보고서 기능 개요, 이 문서의 나머지 부분에서는 실시간 보고서 요청입니다.

신고 요청

실시간 보고서를 요청하려면 RunRealtimeReportRequest 객체를 지정합니다. 다음 요청 매개변수로 시작하는 것이 좋습니다.

  • 측정기준 입력란에 유효한 항목이 1개 이상 있어야 합니다.
  • 측정항목 입력란에 하나 이상의 유효한 항목을 입력해야 합니다.

다음은 추천 필드가 포함된 샘플 요청입니다.

HTTP

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

자바


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

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

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

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

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

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

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

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

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

PHP

google-analytics-data/src/run_realtime_report.php 를 통해 개인정보처리방침을 정의할 수 있습니다.
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\MetricType;
use Google\Analytics\Data\V1beta\RunRealtimeReportRequest;
use Google\Analytics\Data\V1beta\RunRealtimeReportResponse;

/**
 * Runs a realtime report on a Google Analytics 4 property.
 * @param string $propertyId Your GA-4 Property ID
 */
function run_realtime_report(string $propertyId)
{
    // Create an instance of the Google Analytics Data API client library.
    $client = new BetaAnalyticsDataClient();

    // Make an API call.
    $request = (new RunRealtimeReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setDimensions([new Dimension(['name' => 'country'])])
        ->setMetrics([new Metric(['name' => 'activeUsers'])]);
    $response = $client->runRealtimeReport($request);

    printRunRealtimeReportResponse($response);
}

/**
 * Print results of a runRealtimeReport call.
 * @param RunRealtimeReportResponse $response
 */
function printRunRealtimeReportResponse(RunRealtimeReportResponse $response)
{
    printf('%s rows received%s', $response->getRowCount(), PHP_EOL);
    foreach ($response->getDimensionHeaders() as $dimensionHeader) {
        printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL);
    }
    foreach ($response->getMetricHeaders() as $metricHeader) {
        printf(
            'Metric header name: %s (%s)%s',
            $metricHeader->getName(),
            MetricType::name($metricHeader->getType()),
            PHP_EOL
        );
    }

    print 'Report result: ' . PHP_EOL;

    foreach ($response->getRows() as $row) {
        printf(
            '%s %s' . PHP_EOL,
            $row->getDimensionValues()[0]->getValue(),
            $row->getMetricValues()[0]->getValue()
        );
    }
}

Python

google-analytics-data/run_realtime_report.py 를 통해 개인정보처리방침을 정의할 수 있습니다.
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    Dimension,
    Metric,
    RunRealtimeReportRequest,
)

from run_report import print_run_report_response


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


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

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


Node.js

google-analytics-data/run_realtime_report.js 를 통해 개인정보처리방침을 정의할 수 있습니다.
  /**
   * TODO(developer): Uncomment this variable and replace with your GA4
   *   property ID before running the sample.
   */
  // propertyId = 'YOUR-GA4-PROPERTY-ID';

  // Imports the Google Analytics Data API client library.
  const {BetaAnalyticsDataClient} = require('@google-analytics/data');

  // Creates a client.
  const analyticsDataClient = new BetaAnalyticsDataClient();

  // Runs a realtime report on a Google Analytics 4 property.
  async function runRealtimeReport() {
    const [response] = await analyticsDataClient.runRealtimeReport({
      property: `properties/${propertyId}`,
      dimensions: [
        {
          name: 'country',
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
    });
    printRunReportResponse(response);
  }

  runRealtimeReport();

  // Prints results of a runReport call.
  function printRunReportResponse(response) {
    console.log(`${response.rowCount} rows received`);
    response.dimensionHeaders.forEach(dimensionHeader => {
      console.log(`Dimension header name: ${dimensionHeader.name}`);
    });
    response.metricHeaders.forEach(metricHeader => {
      console.log(
        `Metric header name: ${metricHeader.name} (${metricHeader.type})`
      );
    });

    console.log('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

응답 신고

실시간 보고서 응답 주로 헤더와 행입니다. 헤더는 DimensionHeadersMetricHeaders '보고서' 탭에 있는 열이 표시됩니다. 각 행은 DimensionValues로 구성됩니다. MetricValues 및 있습니다. 열의 순서는 요청과 헤더에서 일관됩니다. 지정할 수 있습니다.

다음은 위의 샘플 요청에 대한 샘플 응답입니다.

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

크기

측정기준은 다음에 대한 이벤트 데이터를 설명하고 그룹화합니다. 확인할 수 있습니다 예를 들어 city 측정기준은 도시('파리')를 나타냅니다. '뉴욕')을 입력합니다. 보고서 요청에서 다음 작업을 할 수 있습니다. 0개 이상의 차원을 지정합니다. 실시간 측정기준을 참조하세요. 를 참조하세요.

예를 들어 이 요청은 활성 사용자를 두 개의 측정기준 열로 그룹화합니다.

HTTP

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

자바


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

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

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

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

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

PHP

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\MetricType;
use Google\Analytics\Data\V1beta\RunRealtimeReportRequest;
use Google\Analytics\Data\V1beta\RunRealtimeReportResponse;

/**
 * Runs a realtime report on a Google Analytics 4 property.
 * @param string $propertyId Your GA-4 Property ID
 */
function run_realtime_report_with_multiple_dimensions(string $propertyId)
{
    // Create an instance of the Google Analytics Data API client library.
    $client = new BetaAnalyticsDataClient();

    // Make an API call.
    $request = (new RunRealtimeReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setDimensions([
            new Dimension(['name' => 'country']),
            new Dimension(['name' => 'city']),
        ])
        ->setMetrics([new Metric(['name' => 'activeUsers'])]);
    $response = $client->runRealtimeReport($request);

    printRunRealtimeReportWithMultipleDimensionsResponse($response);
}

/**
 * Print results of a runRealtimeReport call.
 * @param RunRealtimeReportResponse $response
 */
function printRunRealtimeReportWithMultipleDimensionsResponse(RunRealtimeReportResponse $response)
{
    printf('%s rows received%s', $response->getRowCount(), PHP_EOL);
    foreach ($response->getDimensionHeaders() as $dimensionHeader) {
        printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL);
    }
    foreach ($response->getMetricHeaders() as $metricHeader) {
        printf(
            'Metric header name: %s (%s)%s',
            $metricHeader->getName(),
            MetricType::name($metricHeader->getType()),
            PHP_EOL
        );
    }

    print 'Report result: ' . PHP_EOL;

    foreach ($response->getRows() as $row) {
        printf(
            '%s %s' . PHP_EOL,
            $row->getDimensionValues()[0]->getValue(),
            $row->getMetricValues()[0]->getValue()
        );
    }
}

Python

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

from run_report import print_run_report_response


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


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

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


Node.js

  /**
   * TODO(developer): Uncomment this variable and replace with your GA4
   *   property ID before running the sample.
   */
  // propertyId = 'YOUR-GA4-PROPERTY-ID';

  // Imports the Google Analytics Data API client library.
  const {BetaAnalyticsDataClient} = require('@google-analytics/data');

  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests.
  const analyticsDataClient = new BetaAnalyticsDataClient();

  // Runs a realtime report on a Google Analytics 4 property.
  async function runRealtimeReportWithMultipleDimensions() {
    const [response] = await analyticsDataClient.runRealtimeReport({
      property: `properties/${propertyId}`,
      dimensions: [
        {
          name: 'country',
        },
        {
          name: 'city',
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
    });
    printRunReportResponse(response);
  }

  runRealtimeReportWithMultipleDimensions();

  // Prints results of a runReport call.
  function printRunReportResponse(response) {
    console.log(`${response.rowCount} rows received`);
    response.dimensionHeaders.forEach(dimensionHeader => {
      console.log(`Dimension header name: ${dimensionHeader.name}`);
    });
    response.metricHeaders.forEach(metricHeader => {
      console.log(
        `Metric header name: ${metricHeader.name} (${metricHeader.type})`
      );
    });

    console.log('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

예를 들어 보고서 응답의 행에는 다음이 포함될 수 있습니다. 이 행 케이프에서 이벤트가 발생한 웹사이트 또는 앱의 활성 사용자가 47명이라는 의미입니다. 남아프리카 공화국의 도시입니다.

"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": "keyEvents"
      }
    ],
  }

자바


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);
    }
  }
}

PHP

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\MetricType;
use Google\Analytics\Data\V1beta\RunRealtimeReportRequest;
use Google\Analytics\Data\V1beta\RunRealtimeReportResponse;

/**
 * Runs a realtime report on a Google Analytics 4 property.
 * @param string $propertyId Your GA-4 Property ID
 */
function run_realtime_report_with_multiple_metrics(string $propertyId)
{
    // Create an instance of the Google Analytics Data API client library.
    $client = new BetaAnalyticsDataClient();

    // Make an API call.
    $request = (new RunRealtimeReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setDimensions([new Dimension(['name' => 'unifiedScreenName'])])
        ->setMetrics([
            new Metric(['name' => 'screenPageViews']),
            new Metric(['name' => 'conversions']),
        ]);
    $response = $client->runRealtimeReport($request);

    printRunRealtimeReportWithMultipleMetricsResponse($response);
}

/**
 * Print results of a runRealtimeReport call.
 * @param RunRealtimeReportResponse $response
 */
function printRunRealtimeReportWithMultipleMetricsResponse(RunRealtimeReportResponse $response)
{
    printf('%s rows received%s', $response->getRowCount(), PHP_EOL);
    foreach ($response->getDimensionHeaders() as $dimensionHeader) {
        printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL);
    }
    foreach ($response->getMetricHeaders() as $metricHeader) {
        printf(
            'Metric header name: %s (%s)%s',
            $metricHeader->getName(),
            MetricType::name($metricHeader->getType()),
            PHP_EOL
        );
    }

    print 'Report result: ' . PHP_EOL;

    foreach ($response->getRows() as $row) {
        printf(
            '%s %s' . PHP_EOL,
            $row->getDimensionValues()[0]->getValue(),
            $row->getMetricValues()[0]->getValue()
        );
    }
}

Python

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

from run_report import print_run_report_response


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


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

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


Node.js

  /**
   * TODO(developer): Uncomment this variable and replace with your GA4
   *   property ID before running the sample.
   */
  // propertyId = 'YOUR-GA4-PROPERTY-ID';

  // Imports the Google Analytics Data API client library.
  const {BetaAnalyticsDataClient} = require('@google-analytics/data');

  // Creates a client.
  const analyticsDataClient = new BetaAnalyticsDataClient();

  // Runs a realtime report on a Google Analytics 4 property.
  async function runRealtimeReportWithMultipleMetrics() {
    const [response] = await analyticsDataClient.runRealtimeReport({
      // The property parameter value must be in the form `properties/1234`
      // where `1234` is a GA4 property Id.
      property: `properties/${propertyId}`,
      dimensions: [
        {
          name: 'unifiedScreenName',
        },
      ],
      metrics: [
        {
          name: 'screenPageViews',
        },
        {
          name: 'conversions',
        },
      ],
    });
    printRunReportResponse(response);
  }

  runRealtimeReportWithMultipleMetrics();

  // Prints results of a runReport call.
  function printRunReportResponse(response) {
    console.log(`${response.rowCount} rows received`);
    response.dimensionHeaders.forEach(dimensionHeader => {
      console.log(`Dimension header name: ${dimensionHeader.name}`);
    });
    response.metricHeaders.forEach(metricHeader => {
      console.log(
        `Metric header name: ${metricHeader.name} (${metricHeader.type})`
      );
    });

    console.log('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

예를 들어 보고서 응답의 행에는 다음이 포함될 수 있습니다. 이 행 main_menu의 페이지 제목 (웹) 또는 화면 이름 (앱)의 경우 지난 30분 동안 조회수 257회, 주요 이벤트 72회였습니다

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

분 범위

실시간 보고서 요청에서 minuteRanges를 사용할 수 있습니다. 분 범위를 지정하는 필드 이벤트 데이터를 읽어야 합니다. 하나의 쿼리에 최대 2개의 개별 분 범위를 사용할 수 있습니다. 만약 분 범위 사양이 쿼리에 없으면 사용됩니다.

예를 들어 아래 요청은 2분에 대한 활성 사용자 수를 보여줍니다. 범위:

  • 범위 #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,
      }
    ],
  }

자바


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

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

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

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

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

PHP

use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\MetricType;
use Google\Analytics\Data\V1beta\MinuteRange;
use Google\Analytics\Data\V1beta\RunRealtimeReportRequest;
use Google\Analytics\Data\V1beta\RunRealtimeReportResponse;

/**
 * Runs a realtime report on a Google Analytics 4 property. Dimensions field is
 * omitted in the query, which results in total values of active users returned
 * for each minute range in the report.
 *
 * Note the `dateRange` dimension added to the report response automatically as
 * a result of querying multiple minute ranges.
 * @param string $propertyId Your GA-4 Property ID
 */
function run_realtime_report_with_minute_ranges(string $propertyId)
{
    // Create an instance of the Google Analytics Data API client library.
    $client = new BetaAnalyticsDataClient();

    // Make an API call.
    $request = (new RunRealtimeReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setMetrics([
            new Metric(['name' => 'activeUsers']),
        ])
        ->setMinuteRanges([
            new MinuteRange(['name' => '0-4 minutes ago', 'start_minutes_ago' => 4]),
            new MinuteRange(['name' => '25-29 minutes ago', 'start_minutes_ago' => 29, 'end_minutes_ago' => 25]),
        ]);
    $response = $client->runRealtimeReport($request);

    printRunRealtimeReportWithMinuteRangesResponse($response);
}

/**
 * Print results of a runRealtimeReport call.
 * @param RunRealtimeReportResponse $response
 */
function printRunRealtimeReportWithMinuteRangesResponse(RunRealtimeReportResponse $response)
{
    printf('%s rows received%s', $response->getRowCount(), PHP_EOL);
    foreach ($response->getDimensionHeaders() as $dimensionHeader) {
        printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL);
    }
    foreach ($response->getMetricHeaders() as $metricHeader) {
        printf(
            'Metric header name: %s (%s)%s',
            $metricHeader->getName(),
            MetricType::name($metricHeader->getType()),
            PHP_EOL
        );
    }

    print 'Report result: ' . PHP_EOL;
    foreach ($response->getRows() as $row) {
        printf(
            '%s %s' . PHP_EOL,
            $row->getDimensionValues()[0]->getValue(),
            $row->getMetricValues()[0]->getValue()
        );
    }
}

Python

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

from run_report import print_run_report_response


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


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

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

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


Node.js


  // TODO(developer): Uncomment this variable and replace with your
  // Google Analytics 4 property ID before running the sample.
  // propertyId = 'YOUR-GA4-PROPERTY-ID';

  // Imports the Google Analytics Data API client library.
  const {BetaAnalyticsDataClient} = require('@google-analytics/data');

  // Initialize client that will be used to send requests. This client only
  // needs to be created once, and can be reused for multiple requests.
  const analyticsDataClient = new BetaAnalyticsDataClient();

  // Runs a report using two date ranges.
  async function runRealtimeReportWithMinuteRanges() {
    const [response] = await analyticsDataClient.runRealtimeReport({
      property: `properties/${propertyId}`,
      minuteRanges: [
        {
          name: '0-4 minutes ago',
          startMinutesAgo: 4,
          endMinutesAgo: 0,
        },
        {
          name: '25-29 minutes ago',
          startMinutesAgo: 29,
          endMinutesAgo: 25,
        },
      ],
      metrics: [
        {
          name: 'activeUsers',
        },
      ],
    });
    printRunReportResponse(response);
  }

  runRealtimeReportWithMinuteRanges();

  // Prints results of a runReport call.
  function printRunReportResponse(response) {
    console.log(`${response.rowCount} rows received`);
    response.dimensionHeaders.forEach(dimensionHeader => {
      console.log(`Dimension header name: ${dimensionHeader.name}`);
    });
    response.metricHeaders.forEach(metricHeader => {
      console.log(
        `Metric header name: ${metricHeader.name} (${metricHeader.type})`
      );
    });

    console.log('Report result:');
    response.rows.forEach(row => {
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }

다음은 쿼리에 대한 완전한 샘플 응답입니다. 참고: 측정기준 dateRange개가 보고서 응답에 자동으로 추가됨 100% 업타임 체크를 제공합니다

  {
    "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"
  }