逐頁瀏覽結果

Search Ads 360 Reporting API 支援透過 Search 方法分頁查詢結果,方法是在要求中指定 page_size。這會將查詢的結果集拆分為多個回應,每個回應最多包含 page_size 物件。如果未指定 page_size,系統會自動將其設為 10,000 列的最大頁面大小。

例如,使用以下查詢:

SELECT
  ad_group
.id,
  ad_group_criterion
.type,
  ad_group_criterion
.criterion_id,
  ad_group_criterion
.keyword.text,
  ad_group_criterion
.keyword.match_type
FROM ad_group_criterion
WHERE ad_group_criterion.type = KEYWORD

如果帳戶包含 50,000 個關鍵字,且 page_size 設為 1,000,則結果集會在第一個回應中包含 1,000 個 SearchAdsRow 物件,以及一個 next_page_token。如要擷取下一千列,只要以相同的頁面大小再次傳送要求,但請將要求的 page_token 更新為回應的 next_page_token。後續要求中的 page_size 值可能每次都不同。

我們的用戶端程式庫會自動處理分頁作業。您只需逐一檢查回應的資料列。當目前頁面中的所有資料列都已傳回後,用戶端程式庫會自動為您擷取新的資料列頁面,直到整個資料集都已擷取為止。如果您使用 REST 而非 gRPC,則必須明確提出每個新頁面的請求。

Search Ads 360 Reporting API 會在內部快取整個資料集,因此後續要求的速度會比第一個要求快。視使用情況而定,您可以將 page_size 設為 1 到 10,000 之間的任何值。一般來說,為了提升整體效能,您應使用較大的 page_size,因為這樣回覆的往返次數會減少。

分頁範例

JavaPython

// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sample;

import com.beust.jcommander.Parameter;
import com.google.ads.searchads360.v0.lib.SearchAds360Client;
import com.google.ads.searchads360.v0.services.SearchAds360Row;
import com.google.ads.searchads360.v0.services.SearchAds360ServiceClient;
import com.google.ads.searchads360.v0.services.SearchAds360ServiceClient.SearchPagedResponse;
import com.google.ads.searchads360.v0.services.SearchSearchAds360Request;

/** Get campaign details. */
public class GetCampaigns {
 
private static final int PAGE_SIZE = 200;

 
private static class GetCampaignsParams extends CodeSampleParams {

   
@Parameter(names = "--customerId", required = true)
   
private String customerId;

   
@Parameter(names = "--loginCustomerId")
   
private String loginCustomerId;
 
}

 
public static void main(String[] args) {
   
GetCampaignsParams params = new GetCampaignsParams();
   
if (!params.parseArguments(args)) {
     
// Optional: You may pass the loginCustomerId on the command line or specify a loginCustomerId
     
// here (10 digits, no dashes). If neither are set, customerId will be used as
     
// loginCustomerId.
     
// params.loginCustomerId = Long.parseLong("INSERT_LOGIN_CUSTOMER_ID_HERE");
   
}
   
final String loginCustomerId = params.loginCustomerId;
   
final String customerId = params.customerId;

   
try {
     
// Creates a SearchAds360Client with the specified loginCustomerId. If there's
     
// no loginCustomerId, customerId will be used instead.
     
final SearchAds360Client searchAds360Client =
         
SearchAds360Client.newBuilder()
             
.setLoginCustomerId(loginCustomerId == null ? customerId : loginCustomerId)
             
.fromPropertiesFile()
             
.build();
     
// Creates the Search Ads 360 Service client.
     
SearchAds360ServiceClient client = searchAds360Client.create();
     
new GetCampaigns().runExample(client, customerId);
   
} catch (Exception exception) {
     
System.err.printf("Failed with exception: %s%n", exception);
      exception
.printStackTrace();
     
System.exit(1);
   
}
 
}

 
private void runExample(SearchAds360ServiceClient searchAds360ServiceClient, String customerId) {
   
// Creates a query that retrieves all campaigns under the customerId.
   
String query = "SELECT campaign.name, campaign.id, campaign.status FROM campaign";
   
SearchSearchAds360Request request =
       
SearchSearchAds360Request.newBuilder()
           
.setCustomerId(customerId)
           
.setQuery(query)
           
.setPageSize(PAGE_SIZE)
           
.build();

   
// Issues a search request.
   
final SearchPagedResponse searchPagedResponse = searchAds360ServiceClient.search(request);
   
for (SearchAds360Row element : searchPagedResponse.iterateAll()) {
     
System.out.printf(
         
"Campaign found with name '%s', ID %d, and status: %s.%n",
          element
.getCampaign().getName(),
          element
.getCampaign().getId(),
          element
.getCampaign().getStatus());
   
}
 
}
}

下載 GetCampaigns.java

#!/usr/bin/env python
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Retrieves campaigns for a customer using a pagination search request."""

import argparse
import traceback
from google.ads.searchads360.v0.services.types.search_ads360_service import SearchSearchAds360Request
from util_searchads360 import SearchAds360Client

_DEFAULT_PAGE_SIZE
= 10000


def main(client, customer_id, page_size) -> None:
  search_ads_360_service
= client.get_service()

  query
= """
      SELECT
        campaign.name,
        campaign.id,
        campaign.status
      FROM campaign"""


  request
= SearchSearchAds360Request()
  request
.customer_id = customer_id
  request
.query = query
  request
.page_size = page_size

 
# Issues a search request.
  results
= search_ads_360_service.search(request=request)

 
for row in results:
    campaign
= row.campaign
   
print(
        f
'campaign "{campaign.name}" has id {campaign.id} and status {campaign.status.name}'
   
)


if __name__ == "__main__":
 
# SearchAds360Client will read the search-ads-360.yaml configuration file in
 
# the home directory if none is specified.
  search_ads_360_client
= SearchAds360Client.load_from_file()

  parser
= argparse.ArgumentParser(
      description
=("Retrieves campaigns for a customer."))
 
# Arguments to provide to run the example.
  parser
.add_argument(
     
"-c",
     
"--customer_id",
      type
=str,
      required
=True,
      help
="The Search Ads 360 customer ID (10 digits, no dashes).",
 
)

  parser
.add_argument(
     
"-l",
     
"--login_customer_id",
      type
=str,
      required
=False,
      help
="The Search Ads 360 login customer ID (10 digits, no dashes).",
 
)

  args
= parser.parse_args()

  search_ads_360_client
.set_ids(args.customer_id, args.login_customer_id)

 
try:
    main
(search_ads_360_client, args.customer_id, _DEFAULT_PAGE_SIZE)
 
except Exception:  # pylint: disable=broad-except
    traceback
.print_exc()

下載 get_campaigns.py