Google Ads API is returning to beta status. Please read our blog post for more details.

建议服务

建议页面可帮您改进广告系列,它会向您介绍相关的新功能,通过改进出价、关键字和广告增加您的投入回报,以及提升广告系列的整体效果和效率。

建议类型

Google Ads API 目前支持以下建议类型:

建议类型
修正受预算限制的广告系列 CAMPAIGN_BUDGET
添加新关键字 KEYWORD
添加推荐广告 TEXT_AD
采用“目标每次转化费用”出价策略 TARGET_CPA_OPT_IN
采用“尽可能提高转化次数”出价策略 MAXIMIZE_CONVERSIONS_OPT_IN
采用“智能点击付费”出价策略 ENHANCED_CPC_OPT_IN
利用 Google 搜索网络合作伙伴扩大覆盖面 SEARCH_PARTNERS_OPT_IN
采用“尽可能争取更多点击次数”出价策略 MAXIMIZE_CLICKS_OPT_IN
采用优化型广告轮播设置 OPTIMIZE_AD_ROTATION
向广告系列添加附加宣传信息 CALLOUT_EXTENSION
向广告系列添加附加链接 SITELINK_EXTENSION
向广告系列添加附加电话信息 CALL_EXTENSION
更改关键字匹配类型 KEYWORD_MATCH_TYPE
将未使用的预算转移到受限预算 MOVE_UNUSED_BUDGET

获取建议

以下示例代码使用 GoogleAdsService.Search 从帐号中检索所有可用的和被拒绝的建议:

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    String query =
        "SELECT recommendation.type, "
            + "recommendation.campaign, "
            + "recommendation.text_ad_recommendation "
            + "FROM recommendation "
            + "WHERE recommendation.type = TEXT_AD";

    // Creates a request that will retrieve all recommendations using pages of the
    // specified page size.
    SearchGoogleAdsRequest request =
        SearchGoogleAdsRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setPageSize(PAGE_SIZE)
            .setQuery(query)
            .build();
    // Issues the search request.
    SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);

    // Iterates over all rows in all pages and prints the requested field values for the
    // recommendation in each row.
    for (GoogleAdsRow googleAdsRow : searchPagedResponse.iterateAll()) {
      Recommendation recommendation = googleAdsRow.getRecommendation();
      Ad recommendedAd = recommendation.getTextAdRecommendation().getAd();

      System.out.printf(
          "Recommendation ('%s') was found for campaign '%s':%n",
          recommendation.getResourceName(), recommendation.getCampaign().getValue());
      if (recommendedAd.hasExpandedTextAd()) {
        ExpandedTextAdInfo eta = recommendedAd.getExpandedTextAd();
        System.out.printf(
            "\tHeadline 1 = '%s'%n" + "\tHeadline 2 = '%s'%n" + "\tDescription = '%s'%n",
            eta.getHeadlinePart1().getValue(),
            eta.getHeadlinePart2().getValue(),
            eta.getDescription().getValue());
      }
      if (recommendedAd.getDisplayUrl() != null) {
        System.out.printf("\tDisplay URL = '%s'%n", recommendedAd.getDisplayUrl().getValue());
      }
      for (StringValue url : recommendedAd.getFinalUrlsList()) {
        System.out.printf("\tFinal URL = '%s'%n", url.getValue());
      }
      for (StringValue url : recommendedAd.getFinalMobileUrlsList()) {
        System.out.printf("\tFinal Mobile URL = '%s'%n", url.getValue());
      }
    }
  }
}

C#

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

    string query =
        @"SELECT
        recommendation.type,
        recommendation.campaign,
        recommendation.text_ad_recommendation
    FROM
        recommendation
    WHERE
        recommendation.type = TEXT_AD";

    // Create a request that will retrieve all recommendations using pages of the
    // specified page size.
    SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
    {
        CustomerId = customerId.ToString(),
        PageSize = PAGE_SIZE,
        Query = query
    };

    try
    {
        // Issue the search request.
        PagedEnumerable<SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
            service.Search(customerId.ToString(), query);

        // Iterates over all rows in all pages and prints the requested field values
        // for the recommendation in each row.
        foreach (GoogleAdsRow googleAdsRow in searchPagedResponse)
        {
            Recommendation recommendation = googleAdsRow.Recommendation;
            // [START_EXCLUDE]
            Ad recommendedAd = recommendation.TextAdRecommendation.Ad;

            Console.WriteLine($"Recommendation ({recommendation.ResourceName}) was " +
                $"found for campaign {recommendation.Campaign}:");
            if (recommendedAd.ExpandedTextAd != null)
            {
                ExpandedTextAdInfo eta = recommendedAd.ExpandedTextAd;
                Console.WriteLine("\tHeadline 1 = {0}\n\tHeadline 2 = {1}\t" +
                    "Description = {2}",
                    eta.HeadlinePart1, eta.HeadlinePart2, eta.Description);
            }
            Console.WriteLine($"\tDisplay URL = {recommendedAd.DisplayUrl}");
            foreach (string url in recommendedAd.FinalUrls)
            {
                Console.WriteLine($"\tFinal URL = {url}");
            }
            foreach (string url in recommendedAd.FinalMobileUrls)
            {
                Console.WriteLine($"\tFinal Mobile URL = {url}");
            }
            // [END_EXCLUDE]
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
    }
}

PHP

public static function runExample(GoogleAdsClient $googleAdsClient, $customerId)
{
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    // Creates a query that retrieves recommendations for text ads.
    $query = 'SELECT recommendation.type, recommendation.campaign, '
        . 'recommendation.text_ad_recommendation '
        . 'FROM recommendation '
        . 'WHERE recommendation.type = TEXT_AD';

    // Issues a search request by specifying page size.
    $response =
        $googleAdsServiceClient->search($customerId, $query, ['pageSize' => self::PAGE_SIZE]);

    // Iterates over all rows in all pages and prints the requested field values for
    // the recommendation in each row.
    foreach ($response->iterateAllElements() as $googleAdsRow) {
        /** @var GoogleAdsRow $googleAdsRow */
        $recommendation = $googleAdsRow->getRecommendation();
        printf(
            "Recommendation with resource name '%s' was found for campaign "
            . "with resource name '%s':%s",
            $recommendation->getResourceName(),
            $recommendation->getCampaign()->getValue(),
            PHP_EOL
        );
        $recommendedAd = $recommendation->getTextAdRecommendation()->getAd();
        if (!is_null($recommendedAd->getExpandedTextAd())) {
            $recommendedExpandedTextAd = $recommendedAd->getExpandedTextAd();
            printf(
                "\tHeadline part 1 is '%s'.%s",
                $recommendedExpandedTextAd->getHeadlinePart1()->getValue(),
                PHP_EOL
            );
            printf(
                "\tHeadline part 2 is '%s'.%s",
                $recommendedExpandedTextAd->getHeadlinePart2()->getValue(),
                PHP_EOL
            );
            printf(
                "\tDescription is '%s'%s",
                $recommendedExpandedTextAd->getDescription()->getValue(),
                PHP_EOL
            );
        }
        if (!is_null($recommendedAd->getDisplayUrl())) {
            printf(
                "\tDisplay URL is '%s'.%s",
                $recommendedAd->getDisplayUrl()->getValue(),
                PHP_EOL
            );
        }
        foreach ($recommendedAd->getFinalUrls() as $finalUrl) {
            /** @var StringValue $finalUrl */
            printf("\tFinal URL is '%s'.%s", $finalUrl->getValue(), PHP_EOL);
        }
        foreach ($recommendedAd->getFinalMobileUrls() as $finalMobileUrl) {
            /** @var StringValue $finalMobileUrl */
            printf("\tFinal Mobile URL is '%s'.%s", $finalMobileUrl->getValue(), PHP_EOL);
        }
    }
}

Python

def main(client, customer_id, page_size):
    ga_service = client.get_service('GoogleAdsService', version='v1')

    query = ('SELECT recommendation.type, recommendation.campaign, '
             'recommendation.text_ad_recommendation FROM recommendation '
             'WHERE recommendation.type = TEXT_AD')

    results = ga_service.search(customer_id, query=query, page_size=page_size)

    try:
        for row in results:
            recommendation = row.recommendation
            recommended_ad = recommendation.text_ad_recommendation.ad
            print('Recommendation ("%s") was found for campaign "%s".'
                  % (recommendation.resource_name, recommendation.campaign))

            if recommended_ad.display_url:
                print('\tDisplay URL = "%s"' % recommended_ad.display_url)

            for url in recommended_ad.final_urls:
                print('\tFinal URL = "%s"' % url)

            for url in recommended_ad.final_mobile_urls:
                print('\tFinal Mobile URL = "%s"' % url)
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

Ruby

def get_text_ad_recommendations(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

  ga_service = client.service(:GoogleAds)

  query = <<~QUERY
    SELECT recommendation.type, recommendation.campaign,
        recommendation.text_ad_recommendation
    FROM recommendation
    WHERE recommendation.type = TEXT_AD
  QUERY

  response = ga_service.search(customer_id, query, page_size: PAGE_SIZE)

  response.each do |row|
    recommendation = row.recommendation
    recommended_ad = recommendation.text_ad_recommendation.ad

    puts sprintf('Recommendation ("%s") was found for campaign "%s".',
        recommendation.resource_name, recommendation.campaign)
    if recommended_ad.expanded_text_ad
      eta = recommended_ad.expanded_text_ad
      puts sprintf("\tHeadline 1 = '%s'\n\tHeadline2 = '%s'\n" +
          "\tDescription = '%s'", eta.headline_part1, eta.headline_part2,
          eta.description)
    end
    if recommended_ad.display_url
      puts sprintf("\tDisplay URL = '%s'", recommended_ad.display_url)
    end
    recommended_ad.final_urls.each do |url|
      puts sprintf("\tFinal Url = '%s'", url)
    end
    recommended_ad.final_mobile_urls.each do |url|
      puts sprintf("\tFinal Mobile Url = '%s'", url)
    end
  end
end

采纳建议

您可以通过 RecommendationService 向您的帐号应用有效的或被拒绝的建议。要覆盖建议的值,请使用 ApplyRecommendationOperation 和其他参数。

Java

private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, String recommendationId) {
  String recommendationResourceName = ResourceNames.recommendation(customerId, recommendationId);

  ApplyRecommendationOperation.Builder operationBuilder =
      ApplyRecommendationOperation.newBuilder().setResourceName(recommendationResourceName);
  // Each recommendation types has optional parameters to override the recommended values.
  // This is an example to override a recommended ad when a TextAdRecommendation is applied.
  // Please read
  // https://developers.google.com/google-ads/api/reference/rpc/google.ads.googleads.v1.services#google.ads.googleads.v1.services.ApplyRecommendationOperation
  // for details.
  // Note that additional import statements are needed for this example to work. And also, please
  // replace INSERT_AD_ID_HERE with a valid ad ID below.
  //
  // Ad overrideAd = Ad.newBuilder().setId(Int64Value.of(Long.parseLong(
  //     "INSERT_AD_ID_HERE"))).build();
  // operationBuilder.setTextAd(TextAdParameters.newBuilder().
  //     setAd(overrideAd).build()).build();
  List<ApplyRecommendationOperation> operations = new ArrayList<>();
  operations.add(operationBuilder.build());

  try (RecommendationServiceClient recommendationServiceClient =
      googleAdsClient.getLatestVersion().createRecommendationServiceClient()) {
    ApplyRecommendationResponse response =
        recommendationServiceClient.applyRecommendation(
            Long.toString(customerId), operations);
    System.out.printf("Applied %d recommendation:%n", response.getResultsCount());
    for (ApplyRecommendationResult result : response.getResultsList()) {
      System.out.println(result.getResourceName());
    }
  }
}

C#

public void Run(GoogleAdsClient client, long customerId, long recommendationId)
{
    // Get the RecommendationServiceClient.
    RecommendationServiceClient service = client.GetService(
        Services.V1.RecommendationService);

    ApplyRecommendationOperation operation = new ApplyRecommendationOperation()
    {
        ResourceName = ResourceNames.Recommendation(customerId, recommendationId),

        // Each recommendation types has optional parameters to override the recommended
        // values. For example, you can override a recommended ad when a
        // TextAdRecommendation is applied, as shown below.
        // Please read https://developers.google.com/google-ads/api/reference/rpc/google.ads.googleads.v0.services#google.ads.googleads.v0.services.ApplyRecommendationOperation
        // for details.
        // TextAd = new TextAdParameters() {
        //   Ad = new Ad() {
        //     Id = long.Parse("INSERT_AD_ID_HERE")
        //   }
        // }
    };

    try
    {
        ApplyRecommendationResponse response = service.ApplyRecommendation(
            customerId.ToString(), new ApplyRecommendationOperation[] {
                operation
            });
        Console.WriteLine($"Applied {0} recommendation(s):", response.Results.Count);
        foreach (ApplyRecommendationResult result in response.Results)
        {
            Console.WriteLine($"- {result.ResourceName}");
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
    }
}

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    $customerId,
    $recommendationId
) {
    $recommendationResourceName =
        ResourceNames::forRecommendation($customerId, $recommendationId);

    $applyRecommendationOperation = new ApplyRecommendationOperation();
    $applyRecommendationOperation->setResourceName($recommendationResourceName);

    // Each recommendation type has optional parameters to override the recommended values.
    // This is an example to override a recommended ad when a TextAdRecommendation is applied.
    // For details, please read
    // https://developers.google.com/google-ads/api/reference/rpc/google.ads.googleads.v1.services#google.ads.googleads.v1.services.ApplyRecommendationOperation.
    /*
    $overridingAd = new Ad([
        'id' => new Int64Value(['value' => 'INSERT_AD_ID_AS_INTEGER_HERE'])
    ]);
    $applyRecommendationOperation->setTextAd(new TextAdParameters(['ad' => $overridingAd]));
    */
    // Issues a mutate request to apply the recommendation.
    $recommendationServiceClient = $googleAdsClient->getRecommendationServiceClient();
    $response = $recommendationServiceClient->applyRecommendation(
        $customerId,
        [$applyRecommendationOperation]
    );
    /** @var Recommendation $appliedRecommendation */
    $appliedRecommendation = $response->getResults()[0];

    printf(
        "Applied recommendation with resource name: '%s'.%s",
        $appliedRecommendation->getResourceName(),
        PHP_EOL
    );
}

Python

def main(client, customer_id, recommendation_id):
    recommendation_service = client.get_service('RecommendationService',
                                                version='v1')

    apply_recommendation_operation = client.get_type(
        'ApplyRecommendationOperation')

    apply_recommendation_operation.resource_name = (
        recommendation_service.recommendation_path(
            customer_id, recommendation_id))

    try:
        recommendation_response = recommendation_service.apply_recommendation(
            customer_id,
            [apply_recommendation_operation])
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

    print('Applied recommendation with resource name: "%s".'
          % recommendation_response.results[0].resource_name)

Ruby

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

  recommendation_resource =
      client.path.recommendation(customer_id, recommendation_id)
  apply_recommendation_operation = client.operation(:ApplyRecommendation)
  apply_recommendation_operation.resource_name = recommendation_resource

  # Each recommendation type has optional parameters to override the recommended
  # values. This is an example to override a recommended ad when a
  # TextAdRecommendation is applied.
  # For details, please read
  # https://developers.google.com/google-ads/api/reference/rpc/google.ads.google_ads.v1.services#google.ads.google_ads.v1.services.ApplyRecommendationOperation
  #
  # overriding_ad = client.resource(:Ad)
  # overriding_ad.id = client.wrapper.int64('INSERT_AD_ID_AS_INTEGER_HERE')
  # text_ad_parameters = client.resource(:TextAdParameters)
  # text_ad_parameters.ad = overriding_ad
  # apply_recommendation_operation.text_ad = text_ad_parameters

  # Issues a mutate request to apply the recommendation.
  recommendation_service = client.service(:Recommendation)
  response = recommendation_service.apply_recommendation(customer_id,
      [apply_recommendation_operation])
  applied_recommendation = response.results.first

  puts sprintf('Applied recommendation with resource name: "%s".',
      applied_recommendation.resource_name)
end

拒绝建议

您可以通过 RecommendationService 拒绝帐号中的建议。该代码结构与采纳建议的非常类似,可通过 DismissRecommendationOperationRecommendationService.DismissRecommendation 实现。