GoogleAdsService'i kullanarak rapor yayınlama

Google Ads API öğelerini ve raporlama verilerini almak için aşağıdaki yöntemlerden birini kullanın:

İki yöntem arasındaki temel farklar şunlardır:

GoogleAdsService.SearchStream GoogleAdsService.Search
Üretim kodu için uygundur. Evet Evet
Hizmet GoogleAdsService GoogleAdsService
Senaryo Nesneler ve raporlar getiriliyor Nesneler ve raporlar getiriliyor
Yanıt GoogleAdsRow nesnelerinin akışı GoogleAdsRow nesnelerinin sayfaları
Yanıtın alanları Yalnızca sorguda belirtilenler Yalnızca sorguda belirtilenler
Günlük sınırlar Erişim düzeylerine dayalı günlük sınırlar Erişim düzeylerine dayalı günlük sınırlar

Search, bir raporun tamamını indirmek için birden fazla sayfalandırılmış istek gönderirken SearchStream, rapor boyutundan bağımsız olarak tek bir istek gönderir ve Google Ads API ile kalıcı bir gRPC bağlantısı başlatır.

SearchStream için veri paketleri hemen SearchGoogleAdsStreamResponse nesnelik gruplar halinde indirilmeye başlar. Kodunuz, tüm akışın bitmesini beklemeden gelen gruplar üzerinde iterasyon yapabilir.

Search yanıtının her bir sayfasını istemek için gereken gidiş dönüş ağ süresini ortadan kaldıran SearchStream, özellikle büyük raporlar için sayfalara ayırmaya kıyasla daha iyi performans sunar.

Örnek

Bu örnekte, 100,000 satırdan oluşan bir rapor incelenmektedir. Aşağıdaki tabloda, iki yöntem arasındaki istek ve yanıt farklılıkları açıklanmaktadır:

SearchStream Ara
Sayfa boyutu Geçerli Değil Sayfa başına 10.000 satır
API isteklerinin sayısı 1 istek 10 istek
API yanıtlarının sayısı 1 sürekli akış 10 yanıt

Performans faktörleri

Çoğu kullanım alanında, aşağıdaki nedenlerden dolayı Search yerine SearchStream kullanmanızı öneririz:

  • Tek sayfalık raporlar (10.000 satırın altında): İki yöntem arasında önemli bir performans farkı yoktur.
  • Çok sayfalı raporlar: Genellikle SearchStream daha hızlıdır. Bunun nedeni, birden fazla ağ gidiş dönüşünün önlenmesi ve disk önbelleğinden okuma veya yazma işleminin daha az etkili olmasıdır.
  • Bellek verimliliği: SearchStream ile büyük raporları işlerken, bellek yetersizliği (OOM) hatalarını önlemek için tüm satırları aynı anda belleğe almak yerine akış parçaları arasında yineleme yapın ve satırları geldikleri gibi işleyin.
  • Bağlantı esnekliği: SearchStream, kalıcı bir bağlantıya dayandığından uzun süreli akışlar, ağ kesintileri veya son tarih zaman aşımları nedeniyle kesintiye uğrayabilir. Uygun RPC zaman aşımlarını yapılandırın ve geçici akış hataları için yeniden deneme mantığını uygulayın.

Hız sınırları

Her iki yöntemin günlük işlem sınırları, Google Cloud projenizin standart sınırlarına ve erişim düzeylerine tabidir. Tek bir mantıksal rapor sorgusu, sonucun SearchStream ile akış olarak mı yoksa page_token ile Search kullanılarak birden fazla önbelleğe alınmış sayfadan mı alındığına bakılmaksızın günlük işlem kotanızda bir işlem olarak sayılır. Ancak her sayfalara ayrılmış Search isteği, kısa vadeli sıklık sınırları açısından ayrı bir RPC çağrısı olarak sayılır.

Kod örneği

Aşağıdaki kod örneğinde, istemci kitaplıklarını kullanarak nasıl yayın raporu sorgusu yürütüleceği gösterilmektedir:

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    String query = "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id";
    // Constructs the SearchGoogleAdsStreamRequest.
    SearchGoogleAdsStreamRequest request =
        SearchGoogleAdsStreamRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setQuery(query)
            .build();

    // Creates and issues a search Google Ads stream request that will retrieve all campaigns.
    ServerStream<SearchGoogleAdsStreamResponse> stream =
        googleAdsServiceClient.searchStreamCallable().call(request);

    // Iterates through and prints all of the results in the stream response.
    for (SearchGoogleAdsStreamResponse response : stream) {
      for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
        System.out.printf(
            "Campaign with ID %d and name '%s' was found.%n",
            googleAdsRow.getCampaign().getId(), googleAdsRow.getCampaign().getName());
      }
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V25.GoogleAdsService);

    // Create a query that will retrieve all campaigns.
    string query = @"SELECT
                    campaign.id,
                    campaign.name,
                    campaign.network_settings.target_content_network
                FROM campaign
                ORDER BY campaign.id";

    try
    {
        // Issue a search request.
        googleAdsService.SearchStream(customerId.ToString(), query,
            delegate (SearchGoogleAdsStreamResponse resp)
            {
                foreach (GoogleAdsRow googleAdsRow in resp.Results)
                {
                    Console.WriteLine("Campaign with ID {0} and name '{1}' was found.",
                        googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name);
                }
            }
        );
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    // Creates a query that retrieves all campaigns.
    $query = 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id';
    // Issues a search stream request.
    /** @var GoogleAdsServerStreamDecorator $stream */
    $stream = $googleAdsServiceClient->searchStream(
        SearchGoogleAdsStreamRequest::build($customerId, $query)
    );

    // Iterates over all rows in all messages and prints the requested field values for
    // the campaign in each row.
    foreach ($stream->iterateAllElements() as $googleAdsRow) {
        /** @var GoogleAdsRow $googleAdsRow */
        printf(
            "Campaign with ID %d and name '%s' was found.%s",
            $googleAdsRow->getCampaign()->getId(),
            $googleAdsRow->getCampaign()->getName(),
            PHP_EOL
        );
    }
}
      

Python

def main(client: GoogleAdsClient, customer_id: str) -> None:
    ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService")

    query: str = """
        SELECT
          campaign.id,
          campaign.name
        FROM campaign
        ORDER BY campaign.id"""

    # Issues a search request using streaming.
    stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream(
        customer_id=customer_id, query=query
    )

    for batch in stream:
        rows: List[GoogleAdsRow] = batch.results
        for row in rows:
            print(
                f"Campaign with ID {row.campaign.id} and name "
                f'"{row.campaign.name}" was found.'
            )
      

Ruby

def get_campaigns(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  responses = client.service.google_ads.search_stream(
    customer_id: customer_id,
    query: 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id',
  )

  responses.each do |response|
    response.results.each do |row|
      puts "Campaign with ID #{row.campaign.id} and name '#{row.campaign.name}' was found."
    end
  end
end
      

Perl

sub get_campaigns {
  my ($api_client, $customer_id) = @_;

  # Create a search Google Ads stream request that will retrieve all campaigns.
  my $search_stream_request =
    Google::Ads::GoogleAds::V25::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      =>
        "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id"
    });

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  # Issue a search request and process the stream response to print the requested
  # field values for the campaign in each row.
  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;
      printf "Campaign with ID %d and name '%s' was found.\n",
        $google_ads_row->{campaign}{id}, $google_ads_row->{campaign}{name};
    });

  return 1;
}
      

curl