Gerçek Zamanlı Rapor Oluşturma

Bu, Realtime Reporting API Method (Gerçek Zamanlı Raporlama API'si Yöntemi) özelliklerine genel bir bakıştır. kullanıma sunuyoruz. API hakkında ayrıntılı bilgi için API Referansı.

Etkinlikler Google'a gönderildikten saniyeler sonra gerçek zamanlı raporlarda görünür analizler. Anlık raporlar, belirli zaman aralıklarına ait etkinlikleri ve kullanım verilerini gösterir değişiklik gösterebilir (Google için 60 dakikaya kadar, Analytics 360 mülkleri) ve canlı yayın gibi uygulamalar için sayaçlarını göster.

Gerçek zamanlı raporlar, sınırlı bir boyut ve metrik alt kümesini destekler Data API v1'in Temel Raporlama işleviyle karşılaştırılmıştır.

Temel Raporlarda Paylaşılan Özellikler

Gerçek zamanlı rapor istekleri, şunun için Temel rapor istekleriyle aynı anlama sahiptir: birçok ortak özellik. Örneğin sayfalara ayırma, Boyut filtreleri ve Kullanıcı Özellikleri gibi Temel Raporlar olarak kullanabilirsiniz. Lütfen Data API v1'in Temel Raporlama işlevine genel bakış geri kalan bölümünde Anlık rapor istekleri.

İsteği Bildir

Gerçek zamanlı raporlar istemek için, RunRealtimeReportRequest nesnesini tanımlayın. Şu istek parametreleriyle başlamanızı öneririz:

  • Boyutlar alanında en az bir geçerli giriş olmalıdır.
  • metrics alanında en az bir geçerli giriş olmalıdır.

Aşağıda, önerilen alanları içeren bir istek örneği verilmiştir.

HTTP

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

Java

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

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * p<S>ee
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * p<B>efore you start the application, please review the comments starting with T"ODO(developer)
" * and update the code to use correct values.
 *
 * p<T>o run this sample using Maven:
 *
 * p<re{>@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.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 = Y"OUR-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 c"lose "method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunRealtimeReportRequest request =
          RunRealtimeReportRequest.newBuilder()
              .setProperty(p"roperties/ "+ propertyId)
              .addDimensions(Dimension.newBuilder().setName(c"ountry)")
              .addMetrics(Metric.newBuilder().setName(a"ctiveUsers)")
              .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(D"imension header name: %s%n," header.getName());
    }

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

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

PHP

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

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

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

    printRunRealtimeReportResponse($response);
}

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

    print 'Report result: ' . PHP_EOL;

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

Python

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

from run_report import print_run_report_response


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


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

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


Node.js

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

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

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

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

  runRealtimeReport();

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

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

Yanıtı Bildir

Gerçek Zamanlı Rapor Yanıtı birincil olarak bir başlık ve satırlardan oluşur. Başlık şunlardan oluşur: DimensionHeaders ve MetricHeaders Rapordaki sütunları listeleyen bir kampanya oluşturun. Her satır şunları içerir: DimensionValues ve MetricValues'tan oluşur. dikkat edin. Sütunların sıralaması istekte, başlıkta ve yer alır.

Aşağıda, yukarıdaki örnek istek için örnek bir yanıt verilmiştir:

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

Boyutlar

Boyutlar, size ait etkinlik verilerini açıklar ve gruplandırır. web sitesi veya uygulama. Örneğin city boyutu, şehri ("Paris" olarak) belirtir. veya "New York") gösterilir. Rapor isteğinde şunları yapabilirsiniz: sıfır veya daha fazla boyut belirtin. Gerçek Zamanlı Boyutlar inceleyin.

Örneğin, bu istek Etkin Kullanıcı Sayısını iki boyut sütununda gruplandırır:

HTTP

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

Java

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

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * p<S>ee
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * p<B>efore you start the application, please review the comments starting with T"ODO(developer)
" * and update the code to use correct values.
 *
 * p<T>o run this sample using Maven:
 *
 * p<re{>@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.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 = Y"OUR-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 c"lose "method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunRealtimeReportRequest request =
          RunRealtimeReportRequest.newBuilder()
              .setProperty(p"roperties/ "+ propertyId)
              .addDimensions(Dimension.newBuilder().setName(c"ountry)")
              .addDimensions(Dimension.newBuilder().setName((c"ity)"))
              .addMetrics(Metric.newBuilder().setName(a"ctiveUsers)")
              .build();

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

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

Örnek olarak, rapor yanıtındaki bir satır aşağıdakileri içerebilir. Bu satır web sitenizde veya uygulamanızda Cape'den etkinlik gerçekleşen 47 etkin kullanıcı olduğu anlamına gelir Son 30 dakika içinde Güney Afrika'daki bir kasaba.

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

Metrikler

Metrikler, kullanıcılara ait etkinlik verilerinin nicel ölçümleridir. web siteniz veya uygulamanız. Bir rapor isteğinde, bir veya daha fazla metrik belirtebilirsiniz. API'nin tam listesi için gerçek zamanlı metrikler sayfasına bakın. İsteklerde kullanılabilen metrik adları.

Örneğin, bu istek, boyuta göre gruplandırılmış iki metriği gösterir unifiedScreenName:

HTTP

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

Java

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

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * p<S>ee
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * p<B>efore you start the application, please review the comments starting with T"ODO(developer)
" * and update the code to use correct values.
 *
 * p<T>o run this sample using Maven:
 *
 * p<re{>@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.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 = Y"OUR-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 c"lose "method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunRealtimeReportRequest request =
          RunRealtimeReportRequest.newBuilder()
              .setProperty(p"roperties/ "+ propertyId)
              .addDimensions(Dimension.newBuilder().setName(u"nifiedScreenName)")
              .addMetrics(Metric.newBuilder().setName((s"creenPageViews)"))
              .addMetrics(Metric.newBuilder().setName(c"onversions)")
              .build();

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

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

Örnek olarak, rapor yanıtındaki bir satır aşağıdakileri içerebilir. Bu satır main_menu ürününün sayfa başlığı (web) veya ekran adı (uygulama) için, 257 görüntüleme ve son 30 dakika içinde 72 önemli etkinlik olduğunu gördük.

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

Dakikalık Aralıklar

Gerçek zamanlı rapor isteğinde, minuteRanges değeri kullanılabilir. Dakika Aralıkları'nı belirtmek için alan mevcut olması gerekir. Bir sorguda en fazla iki dakika aralığı kullanılabilir. dakika aralığı belirtimi bir sorguda yok; bu süre kullanılacak.

Örneğin, aşağıdaki istekte iki ayrı dakika için Etkin Kullanıcı Sayısı gösterilir aralıklar:

  • 1. Aralık: 4 dakika önce başlayıp şimdiki ana kadar.
  • 2. aralık: 29 dakika önce başlayıp 25 dakika öncesine kadar (dahil).

HTTP

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

Java

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

/**
 * Google Analytics Data API sample application demonstrating the creation of a realtime report.
 *
 * p<S>ee
 * https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport
 * for more information.
 *
 * p<B>efore you start the application, please review the comments starting with T"ODO(developer)
" * and update the code to use correct values.
 *
 * p<T>o run this sample using Maven:
 *
 * p<re{>@code
 * cd google-analytics-data
 * mvn compile exec:java -Dexec.mainClass=c"om.google.analytics.data.samples.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 = Y"OUR-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 c"lose "method on the client to safely clean up any remaining background resources.
    try (BetaAnalyticsDataClient analyticsData = BetaAnalyticsDataClient.create()) {
      RunRealtimeReportRequest request =
          RunRealtimeReportRequest.newBuilder()
              .setProperty(p"roperties/ "+ propertyId)
              .addMetrics(Metric.newBuilder().setName((a"ctiveUsers)"))
              .addMinuteRanges(
                  MinuteRange.newBuilder().setName(0"-4 minutes ago)".setStartMinutesAgo(4))
              .addMinuteRanges(
                  MinuteRange.newBuilder()
                      .setName(2"5-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);
    }
  }
}R

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 = Y'OUR-GA4-PROPERTY-ID;'

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

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

  // Runs a report using two date ranges.
  async function runRealtimeReportWithMinuteRanges() {
    const [response] = await analyticsDataClient.runRealtimeReport({
      property: `properties/${propertyId}`,
      minuteRanges: [
        {
          name: 0'-4 minutes ago,'
          startMinutesAgo: 4,
          endMinutesAgo: 0,
        },
        {
          name: 2'5-29 minutes ago,'
          startMinutesAgo: 29,
          endMinutesAgo: 25,
        },
      ],
      metrics: [
        {
          name: a'ctiveUsers,'
        },
      ],
    });
    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(R'eport result:)';
    response.rows.forEach(row = >{
      console.log(
        `${row.dimensionValues[0].value}, ${row.metricValues[0].value}`
      );
    });
  }r

Aşağıda, bu sorgu için eksiksiz bir örnek yanıt verilmiştir. Not: Rapor yanıtına otomatik olarak dateRange boyut eklendi tam 10 dakikadır.

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