Optimization Samples

The code samples below provide examples of common optimization functions using the AdWords API. Client Library.

Estimate keyword traffic

// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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
//
//     http://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 adwords.axis.v201705.optimization;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201705.cm.Criterion;
import com.google.api.ads.adwords.axis.v201705.cm.Keyword;
import com.google.api.ads.adwords.axis.v201705.cm.KeywordMatchType;
import com.google.api.ads.adwords.axis.v201705.cm.Language;
import com.google.api.ads.adwords.axis.v201705.cm.Location;
import com.google.api.ads.adwords.axis.v201705.cm.Money;
import com.google.api.ads.adwords.axis.v201705.o.AdGroupEstimateRequest;
import com.google.api.ads.adwords.axis.v201705.o.CampaignEstimate;
import com.google.api.ads.adwords.axis.v201705.o.CampaignEstimateRequest;
import com.google.api.ads.adwords.axis.v201705.o.KeywordEstimate;
import com.google.api.ads.adwords.axis.v201705.o.KeywordEstimateRequest;
import com.google.api.ads.adwords.axis.v201705.o.PlatformCampaignEstimate;
import com.google.api.ads.adwords.axis.v201705.o.StatsEstimate;
import com.google.api.ads.adwords.axis.v201705.o.TrafficEstimatorResult;
import com.google.api.ads.adwords.axis.v201705.o.TrafficEstimatorSelector;
import com.google.api.ads.adwords.axis.v201705.o.TrafficEstimatorServiceInterface;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;
import java.util.ArrayList;
import java.util.List;

/**
 * This example gets keyword traffic estimates.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class EstimateKeywordTraffic {

  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    runExample(adWordsServices, session);
  }

  public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session) throws Exception {
    // Get the TrafficEstimatorService.
    TrafficEstimatorServiceInterface trafficEstimatorService =
        adWordsServices.get(session, TrafficEstimatorServiceInterface.class);

    // Create keywords. Refer to the TrafficEstimatorService documentation for the maximum
    // number of keywords that can be passed in a single request.
    //   https://developers.google.com/adwords/api/docs/reference/latest/TrafficEstimatorService
    List<Keyword> keywords = new ArrayList<Keyword>();

    Keyword marsCruiseKeyword = new Keyword();
    marsCruiseKeyword.setText("mars cruise");
    marsCruiseKeyword.setMatchType(KeywordMatchType.BROAD);
    keywords.add(marsCruiseKeyword);

    Keyword cheapCruiseKeyword = new Keyword();
    cheapCruiseKeyword.setText("cheap cruise");
    cheapCruiseKeyword.setMatchType(KeywordMatchType.PHRASE);
    keywords.add(cheapCruiseKeyword);

    Keyword cruiseKeyword = new Keyword();
    cruiseKeyword.setText("cruise");
    cruiseKeyword.setMatchType(KeywordMatchType.EXACT);
    keywords.add(cruiseKeyword);

    // Create a keyword estimate request for each keyword.
    List<KeywordEstimateRequest> keywordEstimateRequests = new ArrayList<KeywordEstimateRequest>();
    for (Keyword keyword : keywords) {
      KeywordEstimateRequest keywordEstimateRequest = new KeywordEstimateRequest();
      keywordEstimateRequest.setKeyword(keyword);
      keywordEstimateRequests.add(keywordEstimateRequest);
    }

    // Add a negative keyword to the traffic estimate.
    KeywordEstimateRequest negativeKeywordEstimateRequest = new KeywordEstimateRequest();
    negativeKeywordEstimateRequest.setKeyword(new Keyword(null, null, null, "hiking tour",
        KeywordMatchType.BROAD));
    negativeKeywordEstimateRequest.setIsNegative(true);
    keywordEstimateRequests.add(negativeKeywordEstimateRequest);

    // Create ad group estimate requests.
    List<AdGroupEstimateRequest> adGroupEstimateRequests = new ArrayList<AdGroupEstimateRequest>();
    AdGroupEstimateRequest adGroupEstimateRequest = new AdGroupEstimateRequest();
    adGroupEstimateRequest.setKeywordEstimateRequests(keywordEstimateRequests
        .toArray(new KeywordEstimateRequest[] {}));
    adGroupEstimateRequest.setMaxCpc(new Money(null, 1000000L));
    adGroupEstimateRequests.add(adGroupEstimateRequest);

    // Create campaign estimate requests.
    List<CampaignEstimateRequest> campaignEstimateRequests =
        new ArrayList<CampaignEstimateRequest>();
    CampaignEstimateRequest campaignEstimateRequest = new CampaignEstimateRequest();
    campaignEstimateRequest.setAdGroupEstimateRequests(adGroupEstimateRequests
        .toArray(new AdGroupEstimateRequest[] {}));

    Location unitedStates = new Location();
    unitedStates.setId(2840L);
    Language english = new Language();
    english.setId(1000L);
    campaignEstimateRequest.setCriteria(new Criterion[] {unitedStates, english});
    campaignEstimateRequests.add(campaignEstimateRequest);

    // Create selector.
    TrafficEstimatorSelector selector = new TrafficEstimatorSelector();
    selector.setCampaignEstimateRequests(campaignEstimateRequests
        .toArray(new CampaignEstimateRequest[] {}));

    // Optional: Request a list of campaign level estimates segmented by platform.
    selector.setPlatformEstimateRequested(true);

    // Get traffic estimates.
    TrafficEstimatorResult result = trafficEstimatorService.get(selector);

    // Display traffic estimates.
    if (result != null
        && result.getCampaignEstimates() != null
        && result.getCampaignEstimates().length > 0) {
      CampaignEstimate campaignEstimate = result.getCampaignEstimates()[0];

      // Display the campaign level estimates segmented by platform.
      if (campaignEstimate.getPlatformEstimates() != null) {
        for (PlatformCampaignEstimate platformEstimate : campaignEstimate.getPlatformEstimates()) {
          String platformMessage =
              String.format(
                  "Results for the platform with ID %d and name '%s':%n",
                  platformEstimate.getPlatform().getId(),
                  platformEstimate.getPlatform().getPlatformName());
          displayMeanEstimates(
              platformMessage,
              platformEstimate.getMinEstimate(),
              platformEstimate.getMaxEstimate());
        }
      }

      // Display the keyword estimates.
      KeywordEstimate[] keywordEstimates =
          campaignEstimate.getAdGroupEstimates()[0].getKeywordEstimates();
      for (int i = 0; i < keywordEstimates.length; i++) {
        if (Boolean.TRUE.equals(keywordEstimateRequests.get(i).getIsNegative())) {
          continue;
        }

        Keyword keyword = keywordEstimateRequests.get(i).getKeyword();
        KeywordEstimate keywordEstimate = keywordEstimates[i];

        String keywordMessage =
            String.format(
                "Results for the keyword with text '%s' and match type '%s':%n",
                keyword.getText(), keyword.getMatchType());
        displayMeanEstimates(keywordMessage, keywordEstimate.getMin(), keywordEstimate.getMax());
      }
    } else {
      System.out.println("No traffic estimates were returned.");
    }
  }

  /**
   * Writes the mean estimates for the given min and max estimates to {@code System.out},
   * prefixed with {@code message}.
   */
  private static void displayMeanEstimates(String message, StatsEstimate minEstimate,
      StatsEstimate maxEstimate) {
    // Find the mean of the min and max values.
    Double meanAverageCpc = calculateMean(minEstimate.getAverageCpc(),
        maxEstimate.getAverageCpc());
    Double meanAveragePosition = calculateMean(minEstimate.getAveragePosition(),
        maxEstimate.getAveragePosition());
    Double meanClicks = calculateMean(minEstimate.getClicksPerDay(),
        maxEstimate.getClicksPerDay());
    Double meanTotalCost = calculateMean(minEstimate.getTotalCost(),
        maxEstimate.getTotalCost());

    System.out.println(message);
    System.out.printf("\tEstimated average CPC: %s%n", formatMean(meanAverageCpc));
    System.out.printf("\tEstimated ad position: %s%n", formatMean(meanAveragePosition));
    System.out.printf("\tEstimated daily clicks: %s%n", formatMean(meanClicks));
    System.out.printf("\tEstimated daily cost: %s%n%n", formatMean(meanTotalCost));
  }

  /**
   * Returns a formatted version of {@code mean}, handling nulls.
   */
  private static String formatMean(Double mean) {
    if (mean == null) {
      // Handle nulls separately, else the %.2f format below will
      // truncate 'null' to 'nu'.
      return null;
    }
    return String.format("%.2f", mean);
  }

  /**
   * Returns the mean of the {@code microAmount} of the two Money values if neither is null, else
   * returns null.
   */
  private static Double calculateMean(Money minMoney, Money maxMoney) {
    if (minMoney == null || maxMoney == null) {
      return null;
    }
    return calculateMean(minMoney.getMicroAmount(), maxMoney.getMicroAmount());
  }

  /**
   * Returns the mean of the two Number values if neither is null, else returns null.
   */
  private static Double calculateMean(Number min, Number max) {
    if (min == null || max == null) {
      return null;
    }
    return (min.doubleValue() + max.doubleValue()) / 2;
  }
}

Get campaign criterion bid modifier simulations

// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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
//
//     http://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 adwords.axis.v201705.optimization;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201705.SelectorBuilder;
import com.google.api.ads.adwords.axis.v201705.cm.BidLandscapeLandscapePoint;
import com.google.api.ads.adwords.axis.v201705.cm.CriterionBidLandscape;
import com.google.api.ads.adwords.axis.v201705.cm.CriterionBidLandscapePage;
import com.google.api.ads.adwords.axis.v201705.cm.DataServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.Selector;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;
import com.google.api.ads.adwords.lib.selectorfields.v201705.cm.DataField;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;

/**
 * This example gets all available campaign mobile bid modifier landscapes
 * for a given campaign. To get campaigns, run basicoperations.GetCampaigns.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class GetCampaignCriterionBidModifierSimulations {

  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential =
        new OfflineCredentials.Builder()
            .forApi(Api.ADWORDS)
            .fromFile()
            .build()
            .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session =
        new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();

    Long campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    runExample(adWordsServices, session, campaignId);
  }

  public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session, Long campaignId)
      throws Exception {
    // Get the DataService.
    DataServiceInterface dataService = adWordsServices.get(session, DataServiceInterface.class);

    // Create selector.
    Selector selector =
        new SelectorBuilder()
            .fields(
                DataField.BidModifier,
                DataField.CampaignId,
                DataField.CriterionId,
                DataField.StartDate,
                DataField.EndDate,
                DataField.LocalClicks,
                DataField.LocalCost,
                DataField.LocalImpressions,
                DataField.TotalLocalClicks,
                DataField.TotalLocalCost,
                DataField.TotalLocalImpressions,
                DataField.RequiredBudget)
            .equals(DataField.CampaignId, campaignId.toString())
            .build();

    // Get bid modifier landscapes for campaign criteria.
    CriterionBidLandscapePage page = dataService.getCampaignCriterionBidLandscape(selector);

    // Display bid landscapes.
    if (page.getEntries() != null) {
      for (CriterionBidLandscape criterionBidLandscape : page.getEntries()) {
        System.out.printf(
            "Found campaign-level criterion bid modifier landscape for"
                + " criterion with ID %d, start date '%s', end date '%s', and"
                + " landscape points:%n",
            criterionBidLandscape.getCriterionId(),
            criterionBidLandscape.getStartDate(),
            criterionBidLandscape.getEndDate());

        for (BidLandscapeLandscapePoint bidLandscapePoint :
            criterionBidLandscape.getLandscapePoints()) {
          System.out.printf(
              "  {bid modifier: %.2f => clicks: %d, cost: %d, impressions: %d, "
                  + "total clicks: %d, total cost: %d, total impressions: %d, and "
                  + "required budget: %d%n",
              bidLandscapePoint.getBidModifier(),
              bidLandscapePoint.getClicks(),
              bidLandscapePoint.getCost().getMicroAmount(),
              bidLandscapePoint.getImpressions(),
              bidLandscapePoint.getTotalLocalClicks(),
              bidLandscapePoint.getTotalLocalCost().getMicroAmount(),
              bidLandscapePoint.getTotalLocalImpressions(),
              bidLandscapePoint.getRequiredBudget().getMicroAmount());
        }
      }
    } else {
      System.out.println("No campaign criterion bid modifier landscapes were found");
    }
  }
}

Get keyword bid simulation

// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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
//
//     http://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 adwords.axis.v201705.optimization;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201705.SelectorBuilder;
import com.google.api.ads.adwords.axis.v201705.cm.BidLandscapeLandscapePoint;
import com.google.api.ads.adwords.axis.v201705.cm.CriterionBidLandscape;
import com.google.api.ads.adwords.axis.v201705.cm.CriterionBidLandscapePage;
import com.google.api.ads.adwords.axis.v201705.cm.DataServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.Selector;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;
import com.google.api.ads.adwords.lib.selectorfields.v201705.cm.DataField;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;

/**
 * This example gets a bid landscape for an ad group and a criterion. To get ad
 * groups, run GetAdGroups.java. To get criteria, run GetKeywords.java.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class GetKeywordBidSimulations {

  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    Long adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
    Long criterionId = Long.parseLong("INSERT_CRITERION_ID_HERE");

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    runExample(adWordsServices, session, adGroupId, criterionId);
  }

  public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session, Long adGroupId,
      Long criterionId) throws Exception {
    // Get the DataService.
    DataServiceInterface dataService =
        adWordsServices.get(session, DataServiceInterface.class);

    // Create selector.
    Selector selector = new SelectorBuilder()
        .fields(
            DataField.AdGroupId,
            DataField.CriterionId,
            DataField.StartDate,
            DataField.EndDate,
            DataField.Bid,
            DataField.LocalClicks,
            DataField.LocalCost,
            DataField.LocalImpressions)
        .equals(DataField.AdGroupId, adGroupId.toString())
        .equals(DataField.CriterionId, criterionId.toString())
        .build();

    // Get bid landscape for ad group criteria.
    CriterionBidLandscapePage page = dataService.getCriterionBidLandscape(selector);

    // Display bid landscapes.
    if (page.getEntries() != null) {
      for (CriterionBidLandscape criterionBidLandscape : page.getEntries()) {
        System.out.printf("Criterion bid landscape with ad group ID %d, criterion ID %d, "
            + "start date %s, end date %s, with landscape points:%n",
            criterionBidLandscape.getAdGroupId(), criterionBidLandscape.getCriterionId(), 
            criterionBidLandscape.getStartDate(), criterionBidLandscape.getEndDate());

        for (BidLandscapeLandscapePoint bidLanscapePoint : criterionBidLandscape
            .getLandscapePoints()) {
          System.out.printf("\t{bid: %d clicks: %d cost: %d impressions: %d}%n",
              bidLanscapePoint.getBid().getMicroAmount(), bidLanscapePoint.getClicks(),
              bidLanscapePoint.getCost().getMicroAmount(), bidLanscapePoint.getImpressions());
        }
        System.out.println(" was found.");
      }
    } else {
      System.out.println("No criterion bid landscapes were found.");
    }
  }
}

Get keyword ideas

// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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
//
//     http://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 adwords.axis.v201705.optimization;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201705.cm.Language;
import com.google.api.ads.adwords.axis.v201705.cm.NetworkSetting;
import com.google.api.ads.adwords.axis.v201705.cm.Paging;
import com.google.api.ads.adwords.axis.v201705.o.Attribute;
import com.google.api.ads.adwords.axis.v201705.o.AttributeType;
import com.google.api.ads.adwords.axis.v201705.o.IdeaType;
import com.google.api.ads.adwords.axis.v201705.o.IntegerSetAttribute;
import com.google.api.ads.adwords.axis.v201705.o.LanguageSearchParameter;
import com.google.api.ads.adwords.axis.v201705.o.LongAttribute;
import com.google.api.ads.adwords.axis.v201705.o.NetworkSearchParameter;
import com.google.api.ads.adwords.axis.v201705.o.RelatedToQuerySearchParameter;
import com.google.api.ads.adwords.axis.v201705.o.RequestType;
import com.google.api.ads.adwords.axis.v201705.o.SearchParameter;
import com.google.api.ads.adwords.axis.v201705.o.StringAttribute;
import com.google.api.ads.adwords.axis.v201705.o.TargetingIdea;
import com.google.api.ads.adwords.axis.v201705.o.TargetingIdeaPage;
import com.google.api.ads.adwords.axis.v201705.o.TargetingIdeaSelector;
import com.google.api.ads.adwords.axis.v201705.o.TargetingIdeaServiceInterface;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.common.lib.utils.Maps;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.base.Joiner;
import com.google.common.primitives.Ints;
import java.util.Map;

/**
 * This example gets keywords related to a seed keyword.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class GetKeywordIdeas {

  public static void main(String[] args) throws Exception {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential = new OfflineCredentials.Builder()
        .forApi(Api.ADWORDS)
        .fromFile()
        .build()
        .generateCredential();

    // Construct an AdWordsSession.
    AdWordsSession session = new AdWordsSession.Builder()
        .fromFile()
        .withOAuth2Credential(oAuth2Credential)
        .build();

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    runExample(adWordsServices, session);
  }

  public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session) throws Exception {
    // Get the TargetingIdeaService.
    TargetingIdeaServiceInterface targetingIdeaService =
        adWordsServices.get(session, TargetingIdeaServiceInterface.class);

    // Create selector.
    TargetingIdeaSelector selector = new TargetingIdeaSelector();
    selector.setRequestType(RequestType.IDEAS);
    selector.setIdeaType(IdeaType.KEYWORD);
    selector.setRequestedAttributeTypes(new AttributeType[] {
        AttributeType.KEYWORD_TEXT,
        AttributeType.SEARCH_VOLUME,
        AttributeType.CATEGORY_PRODUCTS_AND_SERVICES});

    // Set selector paging (required for targeting idea service).
    Paging paging = new Paging();
    paging.setStartIndex(0);
    paging.setNumberResults(10);
    selector.setPaging(paging);

    // Create related to query search parameter.
    RelatedToQuerySearchParameter relatedToQuerySearchParameter =
        new RelatedToQuerySearchParameter();
    relatedToQuerySearchParameter.setQueries(new String[] {"mars cruise"});

    // Language setting (optional).
    // The ID can be found in the documentation:
    //   https://developers.google.com/adwords/api/docs/appendix/languagecodes
    // See the documentation for limits on the number of allowed language parameters:
    //   https://developers.google.com/adwords/api/docs/reference/latest/TargetingIdeaService.LanguageSearchParameter
    LanguageSearchParameter languageParameter = new LanguageSearchParameter();
    Language english = new Language();
    english.setId(1000L);
    languageParameter.setLanguages(new Language[] {english});

    // Create network search parameter (optional).
    NetworkSetting networkSetting = new NetworkSetting();
    networkSetting.setTargetGoogleSearch(true);
    networkSetting.setTargetSearchNetwork(false);
    networkSetting.setTargetContentNetwork(false);
    networkSetting.setTargetPartnerSearchNetwork(false);
    
    NetworkSearchParameter networkSearchParameter = new NetworkSearchParameter();
    networkSearchParameter.setNetworkSetting(networkSetting);
    
    selector.setSearchParameters(
        new SearchParameter[] {relatedToQuerySearchParameter, languageParameter,
            networkSearchParameter});

    // Get related keywords.
    TargetingIdeaPage page = targetingIdeaService.get(selector);

    // Display related keywords.
    if (page.getEntries() != null && page.getEntries().length > 0) {
      for (TargetingIdea targetingIdea : page.getEntries()) {
        Map<AttributeType, Attribute> data = Maps.toMap(targetingIdea.getData());
        StringAttribute keyword = (StringAttribute) data.get(AttributeType.KEYWORD_TEXT);

        IntegerSetAttribute categories =
            (IntegerSetAttribute) data.get(AttributeType.CATEGORY_PRODUCTS_AND_SERVICES);
        String categoriesString = "(none)";
        if (categories != null && categories.getValue() != null) {
          categoriesString = Joiner.on(", ").join(Ints.asList(categories.getValue()));
        }
        Long averageMonthlySearches =
            ((LongAttribute) data.get(AttributeType.SEARCH_VOLUME))
                .getValue();
        System.out.printf("Keyword with text '%s', and average monthly search volume %d "
            + "was found with categories: %s%n", keyword.getValue(), averageMonthlySearches,
            categoriesString);
      }
    } else {
      System.out.println("No related keywords were found.");
    }
  }
}

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.