Gerar métricas históricas

O histórico de métricas mostra métricas sobre o desempenho anterior de palavras-chave na Pesquisa Google, incluindo:

  • Média de pesquisas mensais (últimos 12 meses)
  • Volume de pesquisa mensal aproximado
  • Nível de concorrência
  • Índice de concorrência
  • 20o percentil dos lances
  • 80o percentil dos lances

É possível usar métricas históricas para reduzir um grande conjunto de palavras-chave para um tamanho mais gerenciável com base no desempenho. Se você já souber as palavras-chave que quer usar, pule as métricas históricas e vá direto para as métricas de previsão.

Como gerar métricas

Para gerar métricas históricas:

  1. Crie um KeywordPlan, KeywordPlanCampaigns, KeywordPlanAdGroups, KeywordPlanCampaignKeywords e KeywordPlanAdGroupKeywords.
  2. Chame KeywordPlanService.GenerateHistoricalMetrics com esse plano de palavras-chave.

Crie um plano de palavras-chave

Este exemplo de código:

  1. Cria um KeywordPlan. O forecast_period não é necessário para planos de palavras-chave de métricas históricas.
  2. Adiciona uma KeywordPlanCampaign à KeywordPlan que define o lance de CPC, a rede, o local e o idioma da segmentação.
  3. Adiciona KeywordPlanAdGroups à KeywordPlanCampaign e define o lance de CPC no grupo de anúncios.
  4. Adiciona KeywordPlanAdGroupKeywords à KeywordPlanAdGroups com lances de CPC definidos em cada palavra-chave.
  5. Adiciona um KeywordPlanCampaignKeyword ao KeywordPlanCampaign para excluir a palavra-chave da campanha.

Veja algumas dicas para criar seu plano de palavras-chave.

  • Crie os grupos de anúncios com base em temas como relevância dos criativos, categoria de produtos ou custo por clique.
  • Inclua palavras-chave negativas comuns. Por exemplo, se você não estiver no recrutamento, exclua a palavra-chave "jobs".

Java

private void runExample(GoogleAdsClient googleAdsClient, Long customerId) {
  String keywordPlanResource = createKeywordPlan(googleAdsClient, customerId);
  String planCampaignResource =
      createKeywordPlanCampaign(googleAdsClient, customerId, keywordPlanResource);
  String planAdGroupResource =
      createKeywordPlanAdGroup(googleAdsClient, customerId, planCampaignResource);
  createKeywordPlanAdGroupKeywords(googleAdsClient, customerId, planAdGroupResource);
  createKeywordPlanCampaignKeywords(googleAdsClient, customerId, planCampaignResource);
}

/**
 * Creates a keyword plan.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 */
private static String createKeywordPlan(GoogleAdsClient googleAdsClient, Long customerId) {
  KeywordPlan plan =
      KeywordPlan.newBuilder()
          .setName("Keyword plan for traffic estimate #" + getPrintableDateTime())
          .setForecastPeriod(
              KeywordPlanForecastPeriod.newBuilder()
                  .setDateInterval(KeywordPlanForecastInterval.NEXT_QUARTER)
                  .build())
          .build();

  KeywordPlanOperation op = KeywordPlanOperation.newBuilder().setCreate(plan).build();

  try (KeywordPlanServiceClient client =
      googleAdsClient.getLatestVersion().createKeywordPlanServiceClient()) {
    // Adds the keyword plan.
    MutateKeywordPlansResponse response =
        client.mutateKeywordPlans(String.valueOf(customerId), Arrays.asList(op));

    // Displays the results.
    String resourceName = response.getResults(0).getResourceName();
    System.out.printf("Created keyword plan: %s%n", resourceName);
    return resourceName;
  }
}

/**
 * Creates a campaign for the keyword plan.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @param keywordPlanResource the keyword plan resource name.
 */
private static String createKeywordPlanCampaign(
    GoogleAdsClient googleAdsClient, Long customerId, String keywordPlanResource) {
  // Creates a keyword plan campaign.
  KeywordPlanCampaign.Builder campaign =
      KeywordPlanCampaign.newBuilder()
          .setName("Keyword plan campaign #" + getPrintableDateTime())
          .setCpcBidMicros(1_000_000L)
          .setKeywordPlanNetwork(KeywordPlanNetwork.GOOGLE_SEARCH)
          .setKeywordPlan(keywordPlanResource);

  // See https://developers.google.com/google-ads/api/reference/data/geotargets
  // for the list of geo target IDs.
  campaign.addGeoTargets(
      KeywordPlanGeoTarget.newBuilder()
          // Geo-target constant 2840 is for USA.
          .setGeoTargetConstant(ResourceNames.geoTargetConstant(2840))
          .build());

  // See https://developers.google.com/google-ads/api/reference/data/codes-formats#languages
  // for the list of language criteria IDs.
  //
  // Language criteria 1000 is for English.
  campaign.addLanguageConstants(ResourceNames.languageConstant(1000));

  KeywordPlanCampaignOperation op =
      KeywordPlanCampaignOperation.newBuilder().setCreate(campaign).build();

  try (KeywordPlanCampaignServiceClient client =
      googleAdsClient.getLatestVersion().createKeywordPlanCampaignServiceClient()) {
    // Adds the campaign.
    MutateKeywordPlanCampaignsResponse response =
        client.mutateKeywordPlanCampaigns(String.valueOf(customerId), Arrays.asList(op));

    // Displays the result.
    String resourceName = response.getResults(0).getResourceName();
    System.out.printf("Created campaign for keyword plan: %s%n", resourceName);
    return resourceName;
  }
}

/**
 * Creates the ad group for the keyword plan.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @param planCampaignResource plan campaign resource name.
 */
private static String createKeywordPlanAdGroup(
    GoogleAdsClient googleAdsClient, Long customerId, String planCampaignResource) {
  // Creates the keyword plan ad group.
  KeywordPlanAdGroup.Builder adGroup =
      KeywordPlanAdGroup.newBuilder()
          .setKeywordPlanCampaign(planCampaignResource)
          .setName("Keyword plan ad group #" + getPrintableDateTime())
          .setCpcBidMicros(2_500_000L);

  KeywordPlanAdGroupOperation op =
      KeywordPlanAdGroupOperation.newBuilder().setCreate(adGroup).build();
  try (KeywordPlanAdGroupServiceClient client =
      googleAdsClient.getLatestVersion().createKeywordPlanAdGroupServiceClient()) {
    // Adds the ad group.
    MutateKeywordPlanAdGroupsResponse response =
        client.mutateKeywordPlanAdGroups(String.valueOf(customerId), Arrays.asList(op));

    // Displays the result.
    String resourceName = response.getResults(0).getResourceName();
    System.out.println("Created ad group for keyword plan: " + resourceName);
    return resourceName;
  }
}

/**
 * Creates keywords for the keyword plan.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @param planAdGroupResource plan ad group resource name.
 */
private static void createKeywordPlanAdGroupKeywords(
    GoogleAdsClient googleAdsClient, Long customerId, String planAdGroupResource) {
  // Creates the keywords for keyword plan.
  KeywordPlanAdGroupKeyword keyword1 =
      KeywordPlanAdGroupKeyword.newBuilder()
          .setKeywordPlanAdGroup(planAdGroupResource)
          .setCpcBidMicros(2_000_000L)
          .setMatchType(KeywordMatchType.BROAD)
          .setText("mars cruise")
          .build();
  KeywordPlanAdGroupKeyword keyword2 =
      KeywordPlanAdGroupKeyword.newBuilder()
          .setKeywordPlanAdGroup(planAdGroupResource)
          .setCpcBidMicros(1_500_000L)
          .setMatchType(KeywordMatchType.PHRASE)
          .setText("cheap cruise")
          .build();
  KeywordPlanAdGroupKeyword keyword3 =
      KeywordPlanAdGroupKeyword.newBuilder()
          .setKeywordPlanAdGroup(planAdGroupResource)
          .setCpcBidMicros(1_990_000L)
          .setMatchType(KeywordMatchType.EXACT)
          .setText("jupiter cruise")
          .build();

  // Creates an operation for each plan keyword.
  List<KeywordPlanAdGroupKeywordOperation> operations =
      Stream.of(keyword1, keyword2, keyword3)
          .map(kw -> KeywordPlanAdGroupKeywordOperation.newBuilder().setCreate(kw).build())
          .collect(Collectors.toList());

  try (KeywordPlanAdGroupKeywordServiceClient client =
      googleAdsClient.getLatestVersion().createKeywordPlanAdGroupKeywordServiceClient()) {
    // Adds the keywords.
    MutateKeywordPlanAdGroupKeywordsResponse response =
        client.mutateKeywordPlanAdGroupKeywords(String.valueOf(customerId), operations);
    // Displays the results.
    for (MutateKeywordPlanAdGroupKeywordResult result : response.getResultsList()) {
      System.out.printf("Created keyword for keyword plan: %s%n", result.getResourceName());
    }
  }
}

/**
 * Creates negative keywords for the keyword plan.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @param planCampaignResource plan campaign resource name.
 */
private void createKeywordPlanCampaignKeywords(
    GoogleAdsClient googleAdsClient, Long customerId, String planCampaignResource) {
  KeywordPlanCampaignKeyword negativeKeyword =
      KeywordPlanCampaignKeyword.newBuilder()
          .setKeywordPlanCampaign(planCampaignResource)
          .setMatchType(KeywordMatchType.BROAD)
          .setNegative(true)
          .setText("moon walk")
          .build();
  KeywordPlanCampaignKeywordOperation op =
      KeywordPlanCampaignKeywordOperation.newBuilder().setCreate(negativeKeyword).build();

  try (KeywordPlanCampaignKeywordServiceClient client =
      googleAdsClient.getLatestVersion().createKeywordPlanCampaignKeywordServiceClient()) {
    // Adds the negative keyword.
    MutateKeywordPlanCampaignKeywordsResponse response =
        client.mutateKeywordPlanCampaignKeywords(String.valueOf(customerId), Arrays.asList(op));

    // Displays the result.
    String resourceName = response.getResults(0).getResourceName();
    System.out.printf("Created negative keyword for keyword plan: %s%n", resourceName);
  }
}
      

C#

    public void Run(GoogleAdsClient client, long customerId)
    {
        try
        {
            string keywordPlanResource = CreateKeywordPlan(client, customerId);
            string planCampaignResource = CreateKeywordPlanCampaign(client, customerId,
                keywordPlanResource);
            string planAdGroupResource = CreateKeywordPlanAdGroup(client, customerId,
                planCampaignResource);
            CreateKeywordPlanAdGroupKeywords(client, customerId, planAdGroupResource);
            CreateKeywordPlanCampaignNegativeKeywords(client, customerId, planCampaignResource);
        }
        catch (GoogleAdsException e)
        {
            Console.WriteLine("Failure:");
            Console.WriteLine($"Message: {e.Message}");
            Console.WriteLine($"Failure: {e.Failure}");
            Console.WriteLine($"Request ID: {e.RequestId}");
            throw;
        }
    }

    /// <summary>
    /// Creates the keyword plan.
    /// </summary>
    /// <param name="client">The Google Ads client.</param>
    /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
    /// <returns>The newly created keyword plan resource.</returns>
    private string CreateKeywordPlan(GoogleAdsClient client, long customerId)
    {
        // Get the KeywordPlanService.
        KeywordPlanServiceClient serviceClient = client.GetService(
            Services.V13.KeywordPlanService);

        // Create a keyword plan for next quarter forecast.
        KeywordPlan keywordPlan = new KeywordPlan()
        {
            Name = "Keyword plan for traffic estimate #" + ExampleUtilities.GetRandomString(),
            ForecastPeriod = new KeywordPlanForecastPeriod()
            {
                DateInterval = KeywordPlanForecastInterval.NextQuarter
            }
        };

        KeywordPlanOperation operation = new KeywordPlanOperation()
        {
            Create = keywordPlan
        };

        // Add the keyword plan.
        MutateKeywordPlansResponse response = serviceClient.MutateKeywordPlans(
            customerId.ToString(), new KeywordPlanOperation[] { operation });

        // Display the results.
        String planResource = response.Results[0].ResourceName;
        Console.WriteLine($"Created keyword plan: {planResource}.");
        return planResource;
    }

    /// <summary>
    /// Creates the campaign for the keyword plan.
    /// </summary>
    /// <param name="client">The Google Ads client.</param>
    /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
    /// <param name="keywordPlanResource">The keyword plan resource.</param>
    /// <returns>The newly created campaign resource.</returns>
    private string CreateKeywordPlanCampaign(GoogleAdsClient client, long customerId,
        String keywordPlanResource)
    {
        // Get the KeywordPlanCampaignService.
        KeywordPlanCampaignServiceClient serviceClient = client.GetService(
            Services.V13.KeywordPlanCampaignService);

        // Create a keyword plan campaign.
        KeywordPlanCampaign campaign = new KeywordPlanCampaign()
        {
            Name = "Keyword plan campaign #" + ExampleUtilities.GetRandomString(),
            CpcBidMicros = 1_000_000L,
            KeywordPlanNetwork = KeywordPlanNetwork.GoogleSearch,
            KeywordPlan = keywordPlanResource
        };

        // See https://developers.google.com/google-ads/api/reference/data/geotargets
        // for the list of geo target IDs.
        campaign.GeoTargets.Add(new KeywordPlanGeoTarget()
        {
            GeoTargetConstant = ResourceNames.GeoTargetConstant(2840) /* USA */
        });

        // See https://developers.google.com/google-ads/api/reference/data/codes-formats#languages
        // for the list of language criteria IDs.
        campaign.LanguageConstants.Add(ResourceNames.LanguageConstant(1000)); /* English */

        KeywordPlanCampaignOperation operation = new KeywordPlanCampaignOperation()
        {
            Create = campaign
        };

        // Add the campaign.
        MutateKeywordPlanCampaignsResponse response =
            serviceClient.MutateKeywordPlanCampaigns(customerId.ToString(),
                new KeywordPlanCampaignOperation[] { operation });

        // Display the result.
        String planCampaignResource = response.Results[0].ResourceName;
        Console.WriteLine($"Created campaign for keyword plan: {planCampaignResource}.");
        return planCampaignResource;
    }

    /// <summary>
    /// Creates the ad group for the keyword plan.
    /// </summary>
    /// <param name="client">The Google Ads client.</param>
    /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
    /// <param name="planCampaignResource">The resource name of the campaign under which the
    /// ad group is created.</param>
    /// <returns>The newly created ad group resource.</returns>
    private string CreateKeywordPlanAdGroup(GoogleAdsClient client, long customerId,
        string planCampaignResource)
    {
        // Get the KeywordPlanAdGroupService.
        KeywordPlanAdGroupServiceClient serviceClient = client.GetService(
            Services.V13.KeywordPlanAdGroupService);

        // Create the keyword plan ad group.
        KeywordPlanAdGroup adGroup = new KeywordPlanAdGroup()
        {
            KeywordPlanCampaign = planCampaignResource,
            Name = "Keyword plan ad group #" + ExampleUtilities.GetRandomString(),
            CpcBidMicros = 2_500_000L
        };

        KeywordPlanAdGroupOperation operation = new KeywordPlanAdGroupOperation()
        {
            Create = adGroup
        };

        // Add the ad group.
        MutateKeywordPlanAdGroupsResponse response =
            serviceClient.MutateKeywordPlanAdGroups(
                customerId.ToString(), new KeywordPlanAdGroupOperation[] { operation });

        // Display the result.
        String planAdGroupResource = response.Results[0].ResourceName;
        Console.WriteLine($"Created ad group for keyword plan: {planAdGroupResource}.");
        return planAdGroupResource;
    }

    /// <summary>
    /// Creates keywords for the keyword plan.
    /// </summary>
    /// <param name="client">The Google Ads client.</param>
    /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
    /// <param name="planAdGroupResource">The resource name of the ad group under which the
    /// keyword is created.</param>
    private static void CreateKeywordPlanAdGroupKeywords(GoogleAdsClient client,
        long customerId, string planAdGroupResource)
    {
        // Get the KeywordPlanAdGroupKeywordService.
        KeywordPlanAdGroupKeywordServiceClient serviceClient = client.GetService(
            Services.V13.KeywordPlanAdGroupKeywordService);

        // Create the adgroup level keywords for keyword plan.
        KeywordPlanAdGroupKeyword kpAdGroupKeyword1 = new KeywordPlanAdGroupKeyword()
        {
            KeywordPlanAdGroup = planAdGroupResource,
            CpcBidMicros = 2_000_000L,
            MatchType = KeywordMatchType.Broad,
            Text = "mars cruise"
        };

        KeywordPlanAdGroupKeyword kpAdGroupKeyword2 = new KeywordPlanAdGroupKeyword()
        {
            KeywordPlanAdGroup = planAdGroupResource,
            CpcBidMicros = 1_500_000L,
            MatchType = KeywordMatchType.Phrase,
            Text = "cheap cruise"
        };

        KeywordPlanAdGroupKeyword kpAdGroupKeyword3 = new KeywordPlanAdGroupKeyword()
        {
            KeywordPlanAdGroup = planAdGroupResource,
            CpcBidMicros = 1_990_000L,
            MatchType = KeywordMatchType.Exact,
            Text = "jupiter cruise"
        };

        KeywordPlanAdGroupKeyword[] kpAdGroupKeywords = new KeywordPlanAdGroupKeyword[]
        {
            kpAdGroupKeyword1,
            kpAdGroupKeyword2,
            kpAdGroupKeyword3
        };

        // Create an operation for each plan keyword.
        List<KeywordPlanAdGroupKeywordOperation> operations =
            new List<KeywordPlanAdGroupKeywordOperation>();

        foreach (KeywordPlanAdGroupKeyword kpAdGroupKeyword in kpAdGroupKeywords)
        {
            operations.Add(new KeywordPlanAdGroupKeywordOperation
            {
                Create = kpAdGroupKeyword
            });
        }

        // Add the keywords.
        MutateKeywordPlanAdGroupKeywordsResponse response =
            serviceClient.MutateKeywordPlanAdGroupKeywords(customerId.ToString(), operations);

        // Display the results.
        foreach (MutateKeywordPlanAdGroupKeywordResult result in response.Results)
        {
            Console.WriteLine(
                $"Created ad group keyword for keyword plan: {result.ResourceName}.");
        }
        return;
    }

    /// <summary>
    /// Creates campaign negative keywords for the keyword plan.
    /// </summary>
    /// <param name="client">he Google Ads client.</param>
    /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
    /// <param name="planCampaignResource">The resource name of the campaign under which the
    /// negative keyword is created.</param>
    private static void CreateKeywordPlanCampaignNegativeKeywords(GoogleAdsClient client,
        long customerId, string planCampaignResource)
    {
        // Get the KeywordPlanCampaignKeywordService.
        KeywordPlanCampaignKeywordServiceClient service = client.GetService(
            Services.V13.KeywordPlanCampaignKeywordService);

        // Create the campaign negative keyword for the keyword plan.
        KeywordPlanCampaignKeyword kpCampaignNegativeKeyword = new KeywordPlanCampaignKeyword()
        {
            KeywordPlanCampaign = planCampaignResource,
            MatchType = KeywordMatchType.Broad,
            Text = "moon walk",
            Negative = true
        };

        KeywordPlanCampaignKeywordOperation operation = new KeywordPlanCampaignKeywordOperation
        {
            Create = kpCampaignNegativeKeyword
        };

        // Add the campaign negative keyword.
        MutateKeywordPlanCampaignKeywordsResponse response =
            service.MutateKeywordPlanCampaignKeywords(customerId.ToString(),
                new KeywordPlanCampaignKeywordOperation[] { operation });

        // Display the result.
        MutateKeywordPlanCampaignKeywordResult result = response.Results[0];
        Console.WriteLine("Created campaign negative keyword for keyword plan: " +
            $"{result.ResourceName}.");
        return;
    }
}
      

PHP

public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
    $keywordPlanResource = self::createKeywordPlan(
        $googleAdsClient,
        $customerId
    );

    $planCampaignResource = self::createKeywordPlanCampaign(
        $googleAdsClient,
        $customerId,
        $keywordPlanResource
    );

    $planAdGroupResource = self::createKeywordPlanAdGroup(
        $googleAdsClient,
        $customerId,
        $planCampaignResource
    );

    self::createKeywordPlanAdGroupKeywords(
        $googleAdsClient,
        $customerId,
        $planAdGroupResource
    );

    self::createKeywordPlanNegativeCampaignKeywords(
        $googleAdsClient,
        $customerId,
        $planCampaignResource
    );
}

/**
 * Creates a keyword plan.
 *
 * @param GoogleAdsClient $googleAdsClient the Google Ads API client
 * @param int $customerId the customer ID
 * @return string the newly created keyword plan resource
 */
private static function createKeywordPlan(
    GoogleAdsClient $googleAdsClient,
    int $customerId
) {
    // Creates a keyword plan.
    $keywordPlan = new KeywordPlan([
        'name' => 'Keyword plan for traffic estimate #' . Helper::getPrintableDatetime(),
        'forecast_period' => new KeywordPlanForecastPeriod([
            'date_interval' => KeywordPlanForecastInterval::NEXT_QUARTER
        ])
    ]);

    // Creates a keyword plan operation.
    $keywordPlanOperation = new KeywordPlanOperation();
    $keywordPlanOperation->setCreate($keywordPlan);

    // Issues a mutate request to add the keyword plan.
    $keywordPlanServiceClient = $googleAdsClient->getKeywordPlanServiceClient();
    $response = $keywordPlanServiceClient->mutateKeywordPlans(
        $customerId,
        [$keywordPlanOperation]
    );

    $resourceName = $response->getResults()[0]->getResourceName();
    printf("Created keyword plan: '%s'%s", $resourceName, PHP_EOL);

    return $resourceName;
}

/**
 * Creates the campaign for the keyword plan.
 *
 * @param GoogleAdsClient $googleAdsClient the Google Ads API client
 * @param int $customerId the customer ID
 * @param string $keywordPlanResource the keyword plan resource
 * @return string the newly created campaign resource
 */
private static function createKeywordPlanCampaign(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $keywordPlanResource
) {
    // Creates a keyword plan campaign.
    $keywordPlanCampaign = new KeywordPlanCampaign([
        'name' => 'Keyword plan campaign #' . Helper::getPrintableDatetime(),
        'cpc_bid_micros' => 1000000,
        'keyword_plan_network' => KeywordPlanNetwork::GOOGLE_SEARCH,
        'keyword_plan' => $keywordPlanResource,
    ]);

    // See https://developers.google.com/adwords/api/docs/appendix/geotargeting
    // for the list of geo target IDs.
    $keywordPlanCampaign->setGeoTargets([
        new KeywordPlanGeoTarget([
            'geo_target_constant' => ResourceNames::forGeoTargetConstant(2840) // USA
        ])
    ]);

    // See https://developers.google.com/adwords/api/docs/appendix/codes-formats#languages
    // for the list of language criteria IDs.
    // Set English as a language constant.
    $keywordPlanCampaign->setLanguageConstants([ResourceNames::forLanguageConstant(1000)]);

    // Creates a keyword plan campaign operation.
    $keywordPlanCampaignOperation = new KeywordPlanCampaignOperation();
    $keywordPlanCampaignOperation->setCreate($keywordPlanCampaign);

    $keywordPlanCampaignServiceClient =
        $googleAdsClient->getKeywordPlanCampaignServiceClient();
    $response = $keywordPlanCampaignServiceClient->mutateKeywordPlanCampaigns(
        $customerId,
        [$keywordPlanCampaignOperation]
    );

    $planCampaignResource = $response->getResults()[0]->getResourceName();
    printf("Created campaign for keyword plan: '%s'%s", $planCampaignResource, PHP_EOL);

    return $planCampaignResource;
}

/**
 * Creates the ad group for the keyword plan.
 *
 * @param GoogleAdsClient $googleAdsClient the Google Ads API client
 * @param int $customerId the customer ID
 * @param string $planCampaignResource the resource name of the campaign under which the
 *     ad group is created
 * @return string the newly created ad group resource
 */

private static function createKeywordPlanAdGroup(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $planCampaignResource
) {
    // Creates a keyword plan ad group.
    $keywordPlanAdGroup = new KeywordPlanAdGroup([
        'name' => 'Keyword plan ad group #' . Helper::getPrintableDatetime(),
        'cpc_bid_micros' => 2500000,
        'keyword_plan_campaign' => $planCampaignResource
    ]);

    // Creates a keyword plan ad group operation.
    $keywordPlanAdGroupOperation = new KeywordPlanAdGroupOperation();
    $keywordPlanAdGroupOperation->setCreate($keywordPlanAdGroup);

    $keywordPlanAdGroupServiceClient = $googleAdsClient->getKeywordPlanAdGroupServiceClient();
    $response = $keywordPlanAdGroupServiceClient->mutateKeywordPlanAdGroups(
        $customerId,
        [$keywordPlanAdGroupOperation]
    );

    $planAdGroupResource = $response->getResults()[0]->getResourceName();
    printf("Created ad group for keyword plan: '%s'%s", $planAdGroupResource, PHP_EOL);

    return $planAdGroupResource;
}

/**
 * Creates ad group keywords for the keyword plan.
 *
 * @param GoogleAdsClient $googleAdsClient the Google Ads API client
 * @param int $customerId the customer ID
 * @param string $planAdGroupResource the resource name of the ad group under which the
 *     keywords are created
 */
private static function createKeywordPlanAdGroupKeywords(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $planAdGroupResource
) {
    // Creates the ad group keywords for the keyword plan.
    $keywordPlanAdGroupKeyword1 = new KeywordPlanAdGroupKeyword([
        'text' => 'mars cruise',
        'cpc_bid_micros' => 2000000,
        'match_type' => KeywordMatchType::BROAD,
        'keyword_plan_ad_group' => $planAdGroupResource
    ]);

    $keywordPlanAdGroupKeyword2 = new KeywordPlanAdGroupKeyword([
        'text' => 'cheap cruise',
        'cpc_bid_micros' => 15000000,
        'match_type' => KeywordMatchType::PHRASE,
        'keyword_plan_ad_group' => $planAdGroupResource
    ]);

    $keywordPlanAdGroupKeyword3 = new KeywordPlanAdGroupKeyword([
        'text' => 'jupiter cruise',
        'cpc_bid_micros' => 1990000,
        'match_type' => KeywordMatchType::EXACT,
        'keyword_plan_ad_group' => $planAdGroupResource
    ]);

    $keywordPlanAdGroupKeywords =
        [$keywordPlanAdGroupKeyword1, $keywordPlanAdGroupKeyword2, $keywordPlanAdGroupKeyword3];

    // Creates an array of keyword plan ad group keyword operations.
    $keywordPlanAdGroupKeywordOperations = [];

    foreach ($keywordPlanAdGroupKeywords as $keyword) {
        $keywordPlanAdGroupKeywordOperation = new KeywordPlanAdGroupKeywordOperation();
        $keywordPlanAdGroupKeywordOperation->setCreate($keyword);
        $keywordPlanAdGroupKeywordOperations[] = $keywordPlanAdGroupKeywordOperation;
    }

    $keywordPlanAdGroupKeywordServiceClient =
        $googleAdsClient->getKeywordPlanAdGroupKeywordServiceClient();

    // Adds the keyword plan ad group keywords.
    $response = $keywordPlanAdGroupKeywordServiceClient->mutateKeywordPlanAdGroupKeywords(
        $customerId,
        $keywordPlanAdGroupKeywordOperations
    );

    /** @var KeywordPlanAdGroupKeyword $result */
    foreach ($response->getResults() as $result) {
        printf(
            "Created ad group keyword for keyword plan: '%s'%s",
            $result->getResourceName(),
            PHP_EOL
        );
    }
}

/**
 * Creates negative campaign keywords for the keyword plan.
 *
 * @param GoogleAdsClient $googleAdsClient the Google Ads API client
 * @param int $customerId the customer ID
 * @param string $planCampaignResource the resource name of the campaign under which
 *     the keywords are created
 */
private static function createKeywordPlanNegativeCampaignKeywords(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $planCampaignResource
) {
    // Creates a negative campaign keyword for the keyword plan.
    $keywordPlanCampaignKeyword = new KeywordPlanCampaignKeyword([
        'text' => 'moon walk',
        'match_type' => KeywordMatchType::BROAD,
        'keyword_plan_campaign' => $planCampaignResource,
        'negative' => true
    ]);

    $keywordPlanCampaignKeywordOperation = new KeywordPlanCampaignKeywordOperation();
    $keywordPlanCampaignKeywordOperation->setCreate($keywordPlanCampaignKeyword);

    $keywordPlanCampaignKeywordServiceClient =
        $googleAdsClient->getKeywordPlanCampaignKeywordServiceClient();

    // Adds the negative campaign keyword.
    $response = $keywordPlanCampaignKeywordServiceClient->mutateKeywordPlanCampaignKeywords(
        $customerId,
        [$keywordPlanCampaignKeywordOperation]
    );

    /** @var KeywordPlanCampaignKeyword $result */
    foreach ($response->getResults() as $result) {
        printf(
            "Created negative campaign keyword for keyword plan: '%s'%s",
            $result->getResourceName(),
            PHP_EOL
        );
    }
}
      

Python

def main(client, customer_id):
    """Adds a keyword plan, campaign, ad group, etc. to the customer account.

    Also handles errors from the API and prints them.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
    """
    add_keyword_plan(client, customer_id)


def add_keyword_plan(client, customer_id):
    """Adds a keyword plan, campaign, ad group, etc. to the customer account.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    keyword_plan = create_keyword_plan(client, customer_id)
    keyword_plan_campaign = create_keyword_plan_campaign(
        client, customer_id, keyword_plan
    )
    keyword_plan_ad_group = create_keyword_plan_ad_group(
        client, customer_id, keyword_plan_campaign
    )
    create_keyword_plan_ad_group_keywords(
        client, customer_id, keyword_plan_ad_group
    )
    create_keyword_plan_negative_campaign_keywords(
        client, customer_id, keyword_plan_campaign
    )


def create_keyword_plan(client, customer_id):
    """Adds a keyword plan to the given customer account.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.

    Returns:
        A str of the resource_name for the newly created keyword plan.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    keyword_plan_service = client.get_service("KeywordPlanService")
    operation = client.get_type("KeywordPlanOperation")
    keyword_plan = operation.create

    keyword_plan.name = f"Keyword plan for traffic estimate {uuid.uuid4()}"

    forecast_interval = (
        client.enums.KeywordPlanForecastIntervalEnum.NEXT_QUARTER
    )
    keyword_plan.forecast_period.date_interval = forecast_interval

    response = keyword_plan_service.mutate_keyword_plans(
        customer_id=customer_id, operations=[operation]
    )
    resource_name = response.results[0].resource_name

    print(f"Created keyword plan with resource name: {resource_name}")

    return resource_name


def create_keyword_plan_campaign(client, customer_id, keyword_plan):
    """Adds a keyword plan campaign to the given keyword plan.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
        keyword_plan: A str of the keyword plan resource_name this keyword plan
            campaign should be attributed to.create_keyword_plan.

    Returns:
        A str of the resource_name for the newly created keyword plan campaign.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    keyword_plan_campaign_service = client.get_service(
        "KeywordPlanCampaignService"
    )
    operation = client.get_type("KeywordPlanCampaignOperation")
    keyword_plan_campaign = operation.create

    keyword_plan_campaign.name = f"Keyword plan campaign {uuid.uuid4()}"
    keyword_plan_campaign.cpc_bid_micros = 1000000
    keyword_plan_campaign.keyword_plan = keyword_plan

    network = client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH
    keyword_plan_campaign.keyword_plan_network = network

    geo_target = client.get_type("KeywordPlanGeoTarget")
    # Constant for U.S. Other geo target constants can be referenced here:
    # https://developers.google.com/google-ads/api/reference/data/geotargets
    geo_target.geo_target_constant = "geoTargetConstants/2840"
    keyword_plan_campaign.geo_targets.append(geo_target)

    # Constant for English
    language = "languageConstants/1000"
    keyword_plan_campaign.language_constants.append(language)

    response = keyword_plan_campaign_service.mutate_keyword_plan_campaigns(
        customer_id=customer_id, operations=[operation]
    )

    resource_name = response.results[0].resource_name

    print(f"Created keyword plan campaign with resource name: {resource_name}")

    return resource_name


def create_keyword_plan_ad_group(client, customer_id, keyword_plan_campaign):
    """Adds a keyword plan ad group to the given keyword plan campaign.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
        keyword_plan_campaign: A str of the keyword plan campaign resource_name
            this keyword plan ad group should be attributed to.

    Returns:
        A str of the resource_name for the newly created keyword plan ad group.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    operation = client.get_type("KeywordPlanAdGroupOperation")
    keyword_plan_ad_group = operation.create

    keyword_plan_ad_group.name = f"Keyword plan ad group {uuid.uuid4()}"
    keyword_plan_ad_group.cpc_bid_micros = 2500000
    keyword_plan_ad_group.keyword_plan_campaign = keyword_plan_campaign

    keyword_plan_ad_group_service = client.get_service(
        "KeywordPlanAdGroupService"
    )
    response = keyword_plan_ad_group_service.mutate_keyword_plan_ad_groups(
        customer_id=customer_id, operations=[operation]
    )

    resource_name = response.results[0].resource_name

    print(f"Created keyword plan ad group with resource name: {resource_name}")

    return resource_name


def create_keyword_plan_ad_group_keywords(client, customer_id, plan_ad_group):
    """Adds keyword plan ad group keywords to the given keyword plan ad group.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
        plan_ad_group: A str of the keyword plan ad group resource_name
            these keyword plan keywords should be attributed to.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    keyword_plan_ad_group_keyword_service = client.get_service(
        "KeywordPlanAdGroupKeywordService"
    )
    operation = client.get_type("KeywordPlanAdGroupKeywordOperation")
    operations = []

    operation = client.get_type("KeywordPlanAdGroupKeywordOperation")
    keyword_plan_ad_group_keyword1 = operation.create
    keyword_plan_ad_group_keyword1.text = "mars cruise"
    keyword_plan_ad_group_keyword1.cpc_bid_micros = 2000000
    keyword_plan_ad_group_keyword1.match_type = (
        client.enums.KeywordMatchTypeEnum.BROAD
    )
    keyword_plan_ad_group_keyword1.keyword_plan_ad_group = plan_ad_group
    operations.append(operation)

    operation = client.get_type("KeywordPlanAdGroupKeywordOperation")
    keyword_plan_ad_group_keyword2 = operation.create
    keyword_plan_ad_group_keyword2.text = "cheap cruise"
    keyword_plan_ad_group_keyword2.cpc_bid_micros = 1500000
    keyword_plan_ad_group_keyword2.match_type = (
        client.enums.KeywordMatchTypeEnum.PHRASE
    )
    keyword_plan_ad_group_keyword2.keyword_plan_ad_group = plan_ad_group
    operations.append(operation)

    operation = client.get_type("KeywordPlanAdGroupKeywordOperation")
    keyword_plan_ad_group_keyword3 = operation.create
    keyword_plan_ad_group_keyword3.text = "jupiter cruise"
    keyword_plan_ad_group_keyword3.cpc_bid_micros = 1990000
    keyword_plan_ad_group_keyword3.match_type = (
        client.enums.KeywordMatchTypeEnum.EXACT
    )
    keyword_plan_ad_group_keyword3.keyword_plan_ad_group = plan_ad_group
    operations.append(operation)

    response = keyword_plan_ad_group_keyword_service.mutate_keyword_plan_ad_group_keywords(
        customer_id=customer_id, operations=operations
    )

    for result in response.results:
        print(
            "Created keyword plan ad group keyword with resource name: "
            f"{result.resource_name}"
        )


def create_keyword_plan_negative_campaign_keywords(
    client, customer_id, plan_campaign
):
    """Adds a keyword plan negative campaign keyword to the given campaign.

    Args:
        client: An initialized instance of GoogleAdsClient
        customer_id: A str of the customer_id to use in requests.
        plan_campaign: A str of the keyword plan campaign resource_name
            this keyword plan negative keyword should be attributed to.

    Raises:
        GoogleAdsException: If an error is returned from the API.
    """
    keyword_plan_negative_keyword_service = client.get_service(
        "KeywordPlanCampaignKeywordService"
    )
    operation = client.get_type("KeywordPlanCampaignKeywordOperation")

    keyword_plan_campaign_keyword = operation.create
    keyword_plan_campaign_keyword.text = "moon walk"
    keyword_plan_campaign_keyword.match_type = (
        client.enums.KeywordMatchTypeEnum.BROAD
    )
    keyword_plan_campaign_keyword.keyword_plan_campaign = plan_campaign
    keyword_plan_campaign_keyword.negative = True

    response = keyword_plan_negative_keyword_service.mutate_keyword_plan_campaign_keywords(
        customer_id=customer_id, operations=[operation]
    )

    print(
        "Created keyword plan campaign keyword with resource name: "
        f"{response.results[0].resource_name}"
    )
      

Ruby

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

  keyword_plan = create_keyword_plan(client, customer_id)
  plan_campaign = create_keyword_plan_campaign(
    client,
    customer_id,
    keyword_plan,
  )
  plan_ad_group = create_keyword_plan_ad_group(
    client,
    customer_id,
    plan_campaign,
  )
  create_keyword_plan_ad_group_keywords(client, customer_id, plan_ad_group)
  create_keyword_plan_negative_campaign_keywords(client, customer_id, plan_campaign)
end

def create_keyword_plan(client, customer_id)
  operation = client.operation.create_resource.keyword_plan do |kp|
    kp.name = "Keyword plan for traffic estimate ##{(Time.new.to_f * 1000).to_i}"
    kp.forecast_period = client.resource.keyword_plan_forecast_period do |fp|
      fp.date_interval = :NEXT_QUARTER
    end
  end

  keyword_plan_service = client.service.keyword_plan
  response = keyword_plan_service.mutate_keyword_plans(
    customer_id: customer_id,
    operations: [operation],
  )

  resource_name = response.results.first.resource_name
  puts "Created keyword plan: #{resource_name}"

  resource_name
end

def create_keyword_plan_campaign(client, customer_id, keyword_plan)
  operation = client.operation.create_resource.keyword_plan_campaign do |kpc|
    kpc.name = "Keyword plan campaign ##{(Time.new.to_f * 1000).to_i}"
    kpc.cpc_bid_micros = 1_000_000
    kpc.keyword_plan_network = :GOOGLE_SEARCH
    kpc.keyword_plan = keyword_plan

    kpc.geo_targets << client.resource.keyword_plan_geo_target do |gt|
      gt.geo_target_constant = client.path.geo_target_constant(2840) # US
    end

    kpc.language_constants << client.path.language_constant(1000) # English
  end

  kp_campaign_service_client = client.service.keyword_plan_campaign
  response = kp_campaign_service_client.mutate_keyword_plan_campaigns(
    customer_id: customer_id,
    operations: [operation],
  )

  resource_name = response.results.first.resource_name
  puts "Created campaign for keyword plan: #{resource_name}"

  resource_name
end

def create_keyword_plan_ad_group(client, customer_id, plan_campaign)
  operation = client.operation.create_resource.keyword_plan_ad_group do |kpag|
    kpag.name = "Keyword plan ad group ##{(Time.new.to_f * 1000).to_i}"
    kpag.cpc_bid_micros = 2_500_000
    kpag.keyword_plan_campaign = plan_campaign
  end

  kp_ad_group_service = client.service.keyword_plan_ad_group
  response = kp_ad_group_service.mutate_keyword_plan_ad_groups(
    customer_id: customer_id,
    operations: [operation],
  )

  resource_name = response.results.first.resource_name
  puts "Created ad group for keyword plan: #{resource_name}"

  resource_name
end

def create_keyword_plan_ad_group_keywords(client, customer_id, plan_ad_group)
  kpa_keyword1 = client.resource.keyword_plan_ad_group_keyword do |kpak|
    kpak.text = "mars cruise"
    kpak.cpc_bid_micros = 2_000_000
    kpak.match_type = :BROAD
    kpak.keyword_plan_ad_group = plan_ad_group
  end

  kpa_keyword2 = client.resource.keyword_plan_ad_group_keyword do |kpak|
    kpak.text = "cheap cruise"
    kpak.cpc_bid_micros = 1_500_000
    kpak.match_type = :PHRASE
    kpak.keyword_plan_ad_group = plan_ad_group
  end

  kpa_keyword3 = client.resource.keyword_plan_ad_group_keyword do |kpak|
    kpak.text = "jupiter cruise"
    kpak.cpc_bid_micros = 1_990_000
    kpak.match_type = :EXACT
    kpak.keyword_plan_ad_group = plan_ad_group
  end

  operations = [kpa_keyword1, kpa_keyword2, kpa_keyword3].map do |keyword|
    client.operation.create_resource.keyword_plan_ad_group_keyword(keyword)
  end

  kpa_keyword_service = client.service.keyword_plan_ad_group_keyword
  response = kpa_keyword_service.mutate_keyword_plan_ad_group_keywords(
    customer_id: customer_id,
    operations: operations,
  )

  response.results.each do |result|
    puts "Created ad group keyword for keyword plan: #{result.resource_name}"
  end
end

def create_keyword_plan_negative_campaign_keywords(client, customer_id, plan_campaign)
  operation = client.operation.create_resource.keyword_plan_campaign_keyword do |kpck|
    kpck.text = "moon walk"
    kpck.match_type = :BROAD
    kpck.keyword_plan_campaign = plan_campaign
    kpck.negative = true
  end

  kp_campaign_keyword_service = client.service.keyword_plan_campaign_keyword
  response = kp_campaign_keyword_service.mutate_keyword_plan_campaign_keywords(
    customer_id: customer_id,
    operations: [operation],
  )

  puts "Created negative campaign keyword for keyword plan: " +
      "#{response.results.first.resource_name}"
end
      

Perl

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

  my $keyword_plan_resource = create_keyword_plan($api_client, $customer_id);

  my $keyword_plan_campaign_resource =
    create_keyword_plan_campaign($api_client, $customer_id,
    $keyword_plan_resource);

  my $keyword_plan_ad_group_resource =
    create_keyword_plan_ad_group($api_client, $customer_id,
    $keyword_plan_campaign_resource);

  create_keyword_plan_ad_group_keywords($api_client, $customer_id,
    $keyword_plan_ad_group_resource);

  create_keyword_plan_negative_campaign_keywords($api_client, $customer_id,
    $keyword_plan_campaign_resource);

  return 1;
}

# Creates a keyword plan.
sub create_keyword_plan {
  my ($api_client, $customer_id) = @_;

  # Create a keyword plan.
  my $keyword_plan = Google::Ads::GoogleAds::V13::Resources::KeywordPlan->new({
      name           => "Keyword plan for traffic estimate #" . uniqid(),
      forecastPeriod =>
        Google::Ads::GoogleAds::V13::Resources::KeywordPlanForecastPeriod->new({
          dateInterval => NEXT_QUARTER
        })});

  # Create a keyword plan operation.
  my $keyword_plan_operation =
    Google::Ads::GoogleAds::V13::Services::KeywordPlanService::KeywordPlanOperation
    ->new({
      create => $keyword_plan
    });

  # Add the keyword plan.
  my $keyword_plan_resource = $api_client->KeywordPlanService()->mutate({
      customerId => $customer_id,
      operations => [$keyword_plan_operation]})->{results}[0]{resourceName};

  printf "Created keyword plan: '%s'.\n", $keyword_plan_resource;

  return $keyword_plan_resource;
}

# Creates the campaign for the keyword plan.
sub create_keyword_plan_campaign {
  my ($api_client, $customer_id, $keyword_plan_resource) = @_;

  # Create a keyword plan campaign.
  my $keyword_plan_campaign =
    Google::Ads::GoogleAds::V13::Resources::KeywordPlanCampaign->new({
      name               => "Keyword plan campaign #" . uniqid(),
      cpcBidMicros       => 1000000,
      keywordPlanNetwork => GOOGLE_SEARCH,
      keywordPlan        => $keyword_plan_resource
    });

  # See https://developers.google.com/google-ads/api/reference/data/geotargets
  # for the list of geo target IDs.
  $keyword_plan_campaign->{geoTargets} = [
    Google::Ads::GoogleAds::V13::Resources::KeywordPlanGeoTarget->new({
        # Geo target constant 2840 is for USA.
        geoTargetConstant =>
          Google::Ads::GoogleAds::V13::Utils::ResourceNames::geo_target_constant(
          2840)})];

  # See https://developers.google.com/google-ads/api/reference/data/codes-formats#languages
  # for the list of language criteria IDs.
  $keyword_plan_campaign->{languageConstants} = [
    # Language criteria 1000 is for English.
    Google::Ads::GoogleAds::V13::Utils::ResourceNames::language_constant(1000)];

  # Create a keyword plan campaign operation
  my $keyword_plan_campaign_operation =
    Google::Ads::GoogleAds::V13::Services::KeywordPlanCampaignService::KeywordPlanCampaignOperation
    ->new({
      create => $keyword_plan_campaign
    });

  # Add the keyword plan campaign.
  my $keyword_plan_campaign_resource =
    $api_client->KeywordPlanCampaignService()->mutate({
      customerId => $customer_id,
      operations => [$keyword_plan_campaign_operation]}
  )->{results}[0]{resourceName};

  printf "Created campaign for keyword plan: '%s'.\n",
    $keyword_plan_campaign_resource;

  return $keyword_plan_campaign_resource;
}

# Creates the ad group for the keyword plan.
sub create_keyword_plan_ad_group {
  my ($api_client, $customer_id, $keyword_plan_campaign_resource) = @_;

  # Create a keyword plan ad group.
  my $keyword_plan_ad_group =
    Google::Ads::GoogleAds::V13::Resources::KeywordPlanAdGroup->new({
      name                => "Keyword plan ad group #" . uniqid(),
      cpcBidMicros        => 2500000,
      keywordPlanCampaign => $keyword_plan_campaign_resource
    });

  # Create a keyword plan ad group operation.
  my $keyword_plan_ad_group_operation =
    Google::Ads::GoogleAds::V13::Services::KeywordPlanAdGroupService::KeywordPlanAdGroupOperation
    ->new({
      create => $keyword_plan_ad_group
    });

  # Add the keyword plan ad group.
  my $keyword_plan_ad_group_resource =
    $api_client->KeywordPlanAdGroupService()->mutate({
      customerId => $customer_id,
      operations => [$keyword_plan_ad_group_operation]}
  )->{results}[0]{resourceName};

  printf "Created ad group for keyword plan: '%s'.\n",
    $keyword_plan_ad_group_resource;

  return $keyword_plan_ad_group_resource;
}

# Creates ad group keywords for the keyword plan.
sub create_keyword_plan_ad_group_keywords {
  my ($api_client, $customer_id, $keyword_plan_ad_group_resource) = @_;

  # Create the ad group keywords for the keyword plan.
  my $keyword_plan_ad_group_keyword1 =
    Google::Ads::GoogleAds::V13::Resources::KeywordPlanAdGroupKeyword->new({
      text               => "mars cruise",
      cpcBidMicros       => 2000000,
      matchType          => BROAD,
      keywordPlanAdGroup => $keyword_plan_ad_group_resource
    });

  my $keyword_plan_ad_group_keyword2 =
    Google::Ads::GoogleAds::V13::Resources::KeywordPlanAdGroupKeyword->new({
      text               => "cheap cruise",
      cpcBidMicros       => 1500000,
      matchType          => PHRASE,
      keywordPlanAdGroup => $keyword_plan_ad_group_resource
    });

  my $keyword_plan_ad_group_keyword3 =
    Google::Ads::GoogleAds::V13::Resources::KeywordPlanAdGroupKeyword->new({
      text               => "jupiter cruise",
      cpcBidMicros       => 1990000,
      matchType          => EXACT,
      keywordPlanAdGroup => $keyword_plan_ad_group_resource
    });

  # Create an array of keyword plan ad group keyword operations.
  my $operations = [
    map(
      Google::Ads::GoogleAds::V13::Services::KeywordPlanAdGroupKeywordService::KeywordPlanAdGroupKeywordOperation
        ->new(
        {create => $_}
        ),
      (
        $keyword_plan_ad_group_keyword1, $keyword_plan_ad_group_keyword2,
        $keyword_plan_ad_group_keyword3
      ))];

  # Add the keyword plan ad group keywords.
  my $response = $api_client->KeywordPlanAdGroupKeywordService()->mutate({
    customerId => $customer_id,
    operations => $operations
  });

  foreach my $result (@{$response->{results}}) {
    printf "Created ad group keyword for keyword plan: '%s'.\n",
      $result->{resourceName};
  }
}

# Creates negative campaign keywords for the keyword plan.
sub create_keyword_plan_negative_campaign_keywords {
  my ($api_client, $customer_id, $keyword_plan_campaign_resource) = @_;

  # Create a negative campaign keyword for the keyword plan.
  my $keyword_plan_campaign_keyword =
    Google::Ads::GoogleAds::V13::Resources::KeywordPlanCampaignKeyword->new({
      text                => "moon walk",
      matchType           => BROAD,
      negative            => "true",
      keywordPlanCampaign => $keyword_plan_campaign_resource
    });

  # Create a keyword plan campaign keyword operation.
  my $operation =
    Google::Ads::GoogleAds::V13::Services::KeywordPlanCampaignKeywordService::KeywordPlanCampaignKeywordOperation
    ->new({
      create => $keyword_plan_campaign_keyword
    });

  # Add the keyword plan negative campaign keyword.
  my $response = $api_client->KeywordPlanCampaignKeywordService()->mutate({
      customerId => $customer_id,
      operations => [$operation]});

  printf "Created negative campaign keyword for keyword plan: '%s'.\n",
    $response->{results}[0]{resourceName};
}
      

Gerar as métricas

A geração de métricas históricas é semelhante à geração de métricas. Mude o método no exemplo de código para KeywordPlanService.GenerateHistoricalMetrics.

O pré-requisito para este exemplo de código é que um KeywordPlan já exista. Atualize o exemplo de código em Como gerar métricas de previsão para:

  1. Faça uma solicitação a KeywordPlanService.GenerateHistoricalMetrics depois de criar o KeywordPlan.
  2. Itere cada um dos KeywordPlanHistoricalMetrics e exiba cada uma das métricas.

Métricas como o volume de pesquisas são atualizadas mensalmente, considerando o volume de pesquisas do último mês. Esses são os mesmos dados do Google Trends.

Migração da API AdWords

KeywordPlanService.GenerateHistoricalMetrics substitui o método TargetingIdeaService.get da API AdWords por RequestType=STATS. Ele retorna métricas históricas de todas as palavras-chave canônicas presentes no seu plano de palavras-chave.

Como mapear para a IU

KeywordPlanService.GenerateHistoricalMetrics tem uma funcionalidade semelhante no Planejador de palavras-chave da IU. No entanto, a API exige que você crie um KeywordPlan primeiro.

IU do Planejador de palavras-chave API Google Ads
Inserir palavras-chave KeywordPlanCampaignKeyword ou KeywordPlanAdGroupKeyword
Locais KeywordPlanCampaign.geo_targets
Idioma KeywordPlanCampaign.language_constants
Redes de pesquisa KeywordPlanCampaign.keyword_plan_network
Período GenerateHistoricalMetricsRequest.historical_metrics_options
Lance de CPC