একটি প্রতিবেদন তৈরি করুন

এই নির্দেশিকা ব্যাখ্যা করে কিভাবে Google Analytics ডেটা API v1 ব্যবহার করে আপনার অ্যানালিটিক্স ডেটার জন্য একটি মৌলিক প্রতিবেদন তৈরি করতে হয়। Data API v1 থেকে রিপোর্টগুলি আপনি Google Analytics UI- এর প্রতিবেদন বিভাগে তৈরি করতে পারেন এমন রিপোর্টের অনুরূপ।

এই গাইডটি মূল রিপোর্টিং কভার করে, ডেটা API-এর সাধারণ রিপোর্টিং বৈশিষ্ট্য। Data API v1-এ বিশেষায়িত রিয়েলটাইম রিপোর্টিং এবং ফানেল রিপোর্টিংও রয়েছে।

runReport হল প্রশ্নের জন্য প্রস্তাবিত পদ্ধতি, এবং এই নির্দেশিকা জুড়ে সমস্ত উদাহরণে ব্যবহৃত হয়। অন্যান্য মূল রিপোর্টিং পদ্ধতির একটি ওভারভিউ জন্য উন্নত বৈশিষ্ট্য দেখুন. আপনার প্রশ্নগুলি পরীক্ষা করার জন্য ক্যোয়ারী এক্সপ্লোরার ব্যবহার করে দেখুন।

রিপোর্ট ওভারভিউ

প্রতিবেদনগুলি হল একটি Google Analytics সম্পত্তির ইভেন্ট ডেটার সারণী৷ প্রতিটি রিপোর্ট টেবিলে পৃথক সারিতে ডেটা সহ আপনার ক্যোয়ারীতে অনুরোধ করা মাত্রা এবং মেট্রিক্স রয়েছে।

একটি নির্দিষ্ট অবস্থার সাথে মেলে শুধুমাত্র সারি ফেরাতে ফিল্টার ব্যবহার করুন এবং ফলাফলের মাধ্যমে নেভিগেট করার জন্য পৃষ্ঠা সংখ্যা করুন

এখানে একটি নমুনা রিপোর্ট টেবিল যা একটি মাত্রা ( Country ) এবং একটি মেট্রিক ( activeUsers ) দেখায়:

দেশ সক্রিয় ব্যবহারকারী
জাপান 2541
ফ্রান্স 12

একটি ডেটা উৎস উল্লেখ করুন

প্রতিটি runReport অনুরোধের জন্য আপনাকে একটি Google Analytics প্রপার্টি আইডি নির্দিষ্ট করতে হবে। আপনার নির্দিষ্ট করা অ্যানালিটিক্স প্রপার্টি সেই প্রশ্নের জন্য ডেটাসেট হিসেবে ব্যবহার করা হয়। এখানে একটি উদাহরণ:

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

এই অনুরোধের প্রতিক্রিয়াতে শুধুমাত্র আপনার GA_PROPERTY_ID হিসাবে নির্দিষ্ট করা অ্যানালিটিক্স প্রপার্টির ডেটা অন্তর্ভুক্ত রয়েছে।

আপনি যদি ডেটা এপিআই ক্লায়েন্ট লাইব্রেরি ব্যবহার করেন, তাহলে property প্যারামিটারে ডেটা উৎস উল্লেখ করুন, properties/ GA_PROPERTY_ID আকারে। ক্লায়েন্ট লাইব্রেরি ব্যবহার করার উদাহরণগুলির জন্য দ্রুত শুরু নির্দেশিকা দেখুন।

আপনি যদি আপনার রিপোর্টে পরিমাপ প্রোটোকল ইভেন্টগুলি অন্তর্ভুক্ত করতে চান তবে Google Analytics-এ পরিমাপ প্রোটোকল ইভেন্টগুলি পাঠান দেখুন৷

একটি প্রতিবেদন তৈরি করুন

একটি প্রতিবেদন তৈরি করতে, একটি RunReportRequest অবজেক্ট তৈরি করুন। আমরা নিম্নলিখিত পরামিতি দিয়ে শুরু করার পরামর্শ দিই:

  • dateRanges ক্ষেত্রের একটি বৈধ এন্ট্রি।
  • dimensions ক্ষেত্রে অন্তত একটি বৈধ এন্ট্রি।
  • metrics ক্ষেত্রে অন্তত একটি বৈধ এন্ট্রি।

এখানে প্রস্তাবিত ক্ষেত্রগুলির সাথে একটি নমুনা অনুরোধ রয়েছে:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
  {
    "dateRanges": [{ "startDate": "2023-09-01"", "endDate": "2023-09-15" }],
    "dimensions": [{ "name": "country" }],
    "metrics": [{ "name": "activeUsers" }]
  }

জাভা

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

পিএইচপি

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

পাইথন

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/GA_PROPERTY_ID:runReport
  {
    "dateRanges": [{ "startDate": "7daysAgo", "endDate": "yesterday" }],
    "dimensions": [{ "name": "date" }],
    "metrics": [
      {
        "name": "activeUsers"
      },
      {
        "name": "newUsers"
      },
      {
        "name": "totalRevenue"
      }
    ],
  }

জাভা


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

পিএইচপি

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

পাইথন

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 তারিখে (25 অক্টোবর, 2023) আপনার Analytics সম্পত্তির মুদ্রায় 1135 সক্রিয় ব্যবহারকারী, 512 নতুন ব্যবহারকারী এবং 73.0841 মোট রাজস্ব দেখায়।

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

প্রতিক্রিয়া পড়ুন

প্রতিবেদনের প্রতিক্রিয়াতে একটি শিরোনাম এবং ডেটার সারি রয়েছে। হেডারে রয়েছে DimensionHeaders এবং MetricHeaders , যা রিপোর্টের কলামগুলিকে তালিকাভুক্ত করে। প্রতিটি সারিতে DimensionValues এবং MetricValues থাকে। কলামের ক্রম অনুরোধ, শিরোনাম এবং সারিতে সামঞ্জস্যপূর্ণ।

পূর্ববর্তী নমুনা অনুরোধের জন্য এখানে একটি নমুনা প্রতিক্রিয়া:

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

গ্রুপ এবং ফিল্টার ডেটা

মাত্রা হল গুণগত বৈশিষ্ট্য যা আপনি আপনার ডেটা গোষ্ঠী এবং ফিল্টার করতে ব্যবহার করতে পারেন। উদাহরণস্বরূপ, city মাত্রা Paris বা New York মতো শহরকে নির্দেশ করে, যেখানে প্রতিটি ইভেন্টের উৎপত্তি হয়েছে। runReport অনুরোধের জন্য মাত্রা ঐচ্ছিক, এবং আপনি প্রতি অনুরোধে নয়টি মাত্রা পর্যন্ত ব্যবহার করতে পারেন।

আপনার ডেটা গ্রুপ এবং ফিল্টার করতে আপনি যে মাত্রাগুলি ব্যবহার করতে পারেন তার সম্পূর্ণ তালিকার জন্য API মাত্রাগুলি দেখুন৷

গ্রুপ

এখানে একটি নমুনা অনুরোধ রয়েছে যা সক্রিয় ব্যবহারকারীদের তিনটি মাত্রায় গোষ্ঠীভুক্ত করে:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
  {
    "dateRanges": [{ "startDate": "7daysAgo", "endDate": "yesterday" }],
    "dimensions": [
      {
        "name": "country"
      },
      {
        "name": "region"
      },
      {
        "name": "city"
      }
    ],
    "metrics": [{ "name": "activeUsers" }]
  }
  ```

জাভা


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

পিএইচপি

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

পাইথন

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 এর একটি টাইম সিরিজ রিপোর্ট প্রদান করে, যখন eventName প্রতিটি date জন্য first_open হয়:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
  {
    "dateRanges": [{ "startDate": "7daysAgo", "endDate": "yesterday" }],
    "dimensions": [{ "name": "date" }],
    "metrics": [{ "name": "eventCount" }],
    "dimensionFilter": {
      "filter": {
        "fieldName": "eventName",
        "stringFilter": {
          "value": "first_open"
        }
      }
    },
  }

জাভা


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

পিএইচপি

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

পাইথন

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 Chrome এবং countryId US হয় তখন এই dimensionFilter নির্বাচন করে:

HTTP

...
"dimensionFilter": {
  "andGroup": {
    "expressions": [
      {
        "filter": {
          "fieldName": "browser",
          "stringFilter": {
            "value": "Chrome"
          }
        }
      },
      {
        "filter": {
          "fieldName": "countryId",
          "stringFilter": {
            "value": "US"
          }
        }
      }
    ]
  }
},
...

জাভা


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

পিএইচপি

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

পাইথন

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"
      }
    }
  }
},
...

জাভা


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

পিএইচপি

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

পাইথন

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 রয়েছে যা ইভেন্ট ডেটা প্রদান করে যেখানে eventName যেকোন purchase , in_app_purchase , এবং app_store_subscription_renew :

HTTP

...
"dimensionFilter": {
    "filter": {
      "fieldName": "eventName",
      "inListFilter": {
        "values": ["purchase",
        "in_app_purchase",
        "app_store_subscription_renew"]
      }
    }
  },
...

জাভা


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

পিএইচপি

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

পাইথন

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/GA_PROPERTY_ID:runReport
  {
    ...
    "limit": 100000,
    "offset": 0
  }

জাভা


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("keyEvents"))
              .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("keyEvents"))
              .addMetrics(Metric.newBuilder().setName("totalRevenue"))
              .setLimit(100000)
              .setOffset(100000)
              .build();

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

পিএইচপি

    // Make an API call.
    $request = (new RunReportRequest())
        ->setProperty('properties/' . $propertyId)
        ->setDateRanges([
            new DateRange([
                'start_date' => '350daysAgo',
                'end_date' => 'yesterday',
            ])
        ])
        ->setDimensions([
            new Dimension(['name' => 'firstUserSource']),
            new Dimension(['name' => 'firstUserMedium']),
            new Dimension(['name' => 'firstUserCampaignName']),
        ])
        ->setMetrics([
            new Metric(['name' => 'sessions']),
            new Metric(['name' => 'keyEvents']),
            new Metric(['name' => 'totalRevenue']),
        ])
        ->setLimit(100000)
        ->setOffset(0);

    $requestCount = 1;
    printf('Sending request #%d' . PHP_EOL, $requestCount);

    $response = $client->runReport($request);

পাইথন

    request = RunReportRequest(
        property=f"properties/{property_id}",
        date_ranges=[DateRange(start_date="365daysAgo", end_date="yesterday")],
        dimensions=[
            Dimension(name="firstUserSource"),
            Dimension(name="firstUserMedium"),
            Dimension(name="firstUserCampaignName"),
        ],
        metrics=[
            Metric(name="sessions"),
            Metric(name="keyEvents"),
            Metric(name="totalRevenue"),
        ],
        limit=100000,
        offset=0,
    )
    response = client.run_report(request)

Node.js

    const [response] = await analyticsDataClient.runReport({
      property: `properties/${propertyId}`,
      dateRanges: [
        {
          startDate: '350daysAgo',
          endDate: 'yesterday',
        },
      ],
      dimensions: [
        {
          name: 'firstUserSource',
        },
        {
          name: 'firstUserMedium',
        },
        {
          name: 'firstUserCampaignName',
        },
      ],
      metrics: [
        {
          name: 'sessions',
        },
        {
          name: 'keyEvents',
        },
        {
          name: 'totalRevenue',
        },
      ],
      limit: 100000,
      offset: 0,
    });

প্রতিক্রিয়াতে rowCount প্যারামিটারটি অনুরোধের limit এবং offset মান থেকে স্বতন্ত্র সারির মোট সংখ্যা নির্দেশ করে। উদাহরণস্বরূপ, যদি প্রতিক্রিয়াটি "rowCount": 272345 , তাহলে সমস্ত ডেটা পুনরুদ্ধার করতে আপনার প্রতিটি 100,000 সারির তিনটি অনুরোধের প্রয়োজন৷

পরবর্তী 100,000 সারির জন্য এখানে একটি নমুনা অনুরোধ। অন্যান্য সমস্ত প্যারামিটার, যেমন dateRange , dimensions এবং metrics প্রথম অনুরোধের মতোই হওয়া উচিত৷

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
  {
    ...
    "limit": 100000,
    "offset": 100000
  }

জাভা

      request =
          RunReportRequest.newBuilder()
              .setProperty("properties/" + propertyId)
              .addDateRanges(
                  DateRange.newBuilder().setStartDate("365daysAgo").setEndDate("yesterday"))
              .addDimensions(Dimension.newBuilder().setName("firstUserSource"))
              .addDimensions(Dimension.newBuilder().setName("firstUserMedium"))
              .addDimensions(Dimension.newBuilder().setName("firstUserCampaignName"))
              .addMetrics(Metric.newBuilder().setName("sessions"))
              .addMetrics(Metric.newBuilder().setName("keyEvents"))
              .addMetrics(Metric.newBuilder().setName("totalRevenue"))
              .setLimit(100000)
              .setOffset(100000)
              .build();

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

পিএইচপি

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

পাইথন

    request = RunReportRequest(
        property=f"properties/{property_id}",
        date_ranges=[DateRange(start_date="365daysAgo", end_date="yesterday")],
        dimensions=[
            Dimension(name="firstUserSource"),
            Dimension(name="firstUserMedium"),
            Dimension(name="firstUserCampaignName"),
        ],
        metrics=[
            Metric(name="sessions"),
            Metric(name="keyEvents"),
            Metric(name="totalRevenue"),
        ],
        limit=100000,
        offset=100000,
    )
    response = client.run_report(request)

Node.js

    const [secondResponse] = await analyticsDataClient.runReport({
      property: `properties/${propertyId}`,
      dateRanges: [
        {
          startDate: '350daysAgo',
          endDate: 'yesterday',
        },
      ],
      dimensions: [
        {
          name: 'firstUserSource',
        },
        {
          name: 'firstUserMedium',
        },
        {
          name: 'firstUserCampaignName',
        },
      ],
      metrics: [
        {
          name: 'sessions',
        },
        {
          name: 'keyEvents',
        },
        {
          name: 'totalRevenue',
        },
      ],
      limit: 100000,
      offset: 100000,
    });

আপনি offset মান ব্যবহার করতে পারেন, উদাহরণস্বরূপ 200000 বা 300000 , পরবর্তী ফলাফলগুলি পুনরুদ্ধার করতে। অন্যান্য সমস্ত প্যারামিটার যেমন dateRange , dimensions এবং metrics প্রথম অনুরোধের মতোই হওয়া উচিত৷

একাধিক তারিখ ব্যাপ্তি ব্যবহার করুন

একটি প্রতিবেদনের অনুরোধ একাধিক dateRanges জন্য ডেটা পুনরুদ্ধার করতে পারে। উদাহরণস্বরূপ, এই প্রতিবেদনটি 2022 এবং 2023 সালের আগস্টের প্রথম দুই সপ্তাহের তুলনা করে:

HTTP

POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runReport
  {
    "dateRanges": [
      {
        "startDate": "2022-08-01",
        "endDate": "2022-08-14"
      },
      {
        "startDate": "2023-08-01",
        "endDate": "2023-08-14"
      }
    ],
    "dimensions": [{ "name": "platform" }],
    "metrics": [{ "name": "activeUsers" }]
  }

জাভা


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

পিএইচপি

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

পাইথন

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

পরবর্তী পদক্ষেপ

ডেটা API v1-এর আরও উন্নত রিপোর্টিং বৈশিষ্ট্যগুলির একটি ওভারভিউয়ের জন্য উন্নত বৈশিষ্ট্য এবং রিয়েলটাইম রিপোর্টিং দেখুন৷