Google Ads API エンティティとレポートデータを取得するには、次のいずれかの方法を使用します。
2 つの方法の主な違いは次のとおりです。
| GoogleAdsService.SearchStream | GoogleAdsService.Search | |
|---|---|---|
| 本番環境コードに適している | はい | はい |
| サービス | GoogleAdsService |
GoogleAdsService |
| シナリオ | オブジェクトとレポートの取得 | オブジェクトとレポートの取得 |
| レスポンス | GoogleAdsRow オブジェクトの Stream |
GoogleAdsRow オブジェクトのページ |
| レスポンスのフィールド | クエリで指定されたもののみ | クエリで指定されたもののみ |
| 1 日の使用上限 | アクセスレベルに基づく 1 日あたりの上限 | アクセスレベルに基づく 1 日あたりの上限 |
SearchStream 対 Search
Search は、レポート全体をダウンロードするために複数のページネーション リクエストを送信しますが、SearchStream は、レポートのサイズに関係なく、単一のリクエストを送信し、Google Ads API との永続的な gRPC 接続を開始します。
SearchStream の場合、データパケットは SearchGoogleAdsStreamResponse オブジェクトのバッチで直ちにダウンロードを開始します。コードは、ストリーム全体が終了するのを待たずに、到着したバッチを反復処理できます。
Search レスポンスの各ページをリクエストするために必要なネットワークの往復時間を排除することで、SearchStream はページングよりもパフォーマンスが向上します。特に大規模なレポートで効果を発揮します。
例
この例では、100,000 行で構成されるレポートを調べます。次の表に、2 つのメソッドのリクエストとレスポンスの違いを示します。
| SearchStream | 検索 | |
|---|---|---|
| ページサイズ | 該当なし | 1 ページあたり 10,000 行 |
| API リクエストの数 | 1 件のリクエスト | 10 件のリクエスト |
| API レスポンスの数 | 1 つの連続ストリーム | 10 件の回答 |
パフォーマンスの要因
ほとんどのユースケースでは、次の理由から Search よりも SearchStream をおすすめします。
- 1 ページのレポート(10,000 行未満): 2 つの方法の間にパフォーマンスの大きな違いはありません。
- 複数ページのレポート: 通常、
SearchStreamの方が高速です。これは、複数のネットワーク ラウンド トリップが回避され、ディスク キャッシュからの読み取りまたは書き込みが要因になりにくいためです。 - メモリ効率:
SearchStreamで大きなレポートを処理する場合、メモリ不足(OOM)エラーを回避するために、すべての行を一度にメモリにバッファリングするのではなく、ストリーム チャンクを反復処理し、行が到着するたびに処理します。 - 接続の復元力:
SearchStreamは永続的な接続に依存しているため、長時間実行されるストリームはネットワークの切断や期限のタイムアウトによって中断される可能性があります。適切な RPC タイムアウトを構成し、一時的なストリーム エラーに対する再試行ロジックを実装します。
レート上限
両方のメソッドの 1 日のオペレーション上限は、Google Cloud プロジェクトの標準の上限とアクセスレベルに準拠します。1 つの論理レポートクエリは、結果が SearchStream でストリーミングされるか、page_token を使用して Search で複数のキャッシュ保存されたページから取得されるかに関係なく、1 日のオペレーション割り当てに対して 1 つのオペレーションとしてカウントされます。ただし、ページングされた Search リクエストは、短期レート上限に対する個々の RPC 呼び出しとしてカウントされます。
サンプルコード
次のコード例は、クライアント ライブラリを使用してストリーミング レポートのクエリを実行する方法を示しています。
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; }