Targeting Samples

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

Add targeting criteria to a campaign

// 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.targeting;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterion;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterionOperation;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterionReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.ConstantOperand;
import com.google.api.ads.adwords.axis.v201705.cm.ConstantOperandConstantType;
import com.google.api.ads.adwords.axis.v201705.cm.ConstantOperandUnit;
import com.google.api.ads.adwords.axis.v201705.cm.Criterion;
import com.google.api.ads.adwords.axis.v201705.cm.Function;
import com.google.api.ads.adwords.axis.v201705.cm.FunctionArgumentOperand;
import com.google.api.ads.adwords.axis.v201705.cm.FunctionOperator;
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.LocationExtensionOperand;
import com.google.api.ads.adwords.axis.v201705.cm.LocationGroups;
import com.google.api.ads.adwords.axis.v201705.cm.NegativeCampaignCriterion;
import com.google.api.ads.adwords.axis.v201705.cm.Operator;
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.Arrays;
import java.util.List;
import javax.annotation.Nullable;

/**
 * This example adds various types of targeting criteria to a campaign. To get
 * campaigns, run GetCampaigns.java
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class AddCampaignTargetingCriteria {

  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.valueOf("INSERT_CAMPAIGN_ID_HERE");
    // Replace the value below with the ID of a feed that has been configured for location
    // targeting, meaning it has an ENABLED FeedMapping with criterionType of 77. Feeds linked to a
    // GMB account automatically have this FeedMapping.
    // If you don't have such a feed, set this value to null.
    Long locationFeedId = Long.valueOf("INSERT_LOCATION_FEED_ID_HERE");

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    runExample(adWordsServices, session, campaignId, locationFeedId);
  }

  public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session,
      Long campaignId, @Nullable Long locationFeedId) throws Exception {
    // Get the CampaignService.
    CampaignCriterionServiceInterface campaignCriterionService =
        adWordsServices.get(session, CampaignCriterionServiceInterface.class);

    // Create locations. The IDs can be found in the documentation or
    // retrieved with the LocationCriterionService.
    Location california = new Location();
    california.setId(21137L);
    Location mexico = new Location();
    mexico.setId(2484L);

    // Create languages. The IDs can be found in the documentation or
    // retrieved with the ConstantDataService.
    Language english = new Language();
    english.setId(1000L);
    Language spanish = new Language();
    spanish.setId(1003L);

    List<Criterion> criteria = new ArrayList<>(Arrays.asList(california, mexico, english, spanish));
    
    // Distance targeting. Area of 10 miles around the locations in the location feed.
    if (locationFeedId != null) {
      LocationGroups radiusLocationGroup = new LocationGroups();
      radiusLocationGroup.setFeedId(locationFeedId);
      ConstantOperand radius = new ConstantOperand();
      radius.setType(ConstantOperandConstantType.DOUBLE);
      radius.setUnit(ConstantOperandUnit.MILES);
      radius.setDoubleValue(10d);
      LocationExtensionOperand distance = new LocationExtensionOperand();
      distance.setRadius(radius);

      Function radiusMatchingFunction = new Function();
      radiusMatchingFunction.setOperator(FunctionOperator.IDENTITY);
      radiusMatchingFunction.setLhsOperand(new FunctionArgumentOperand[] {distance});
      radiusLocationGroup.setMatchingFunction(radiusMatchingFunction);
      
      criteria.add(radiusLocationGroup);
    }

    // Create operations to add each of the criteria above.
    List<CampaignCriterionOperation> operations = new ArrayList<CampaignCriterionOperation>();
    for (Criterion criterion : criteria) {
      CampaignCriterionOperation operation = new CampaignCriterionOperation();
      CampaignCriterion campaignCriterion = new CampaignCriterion();
      campaignCriterion.setCampaignId(campaignId);
      campaignCriterion.setCriterion(criterion);
      operation.setOperand(campaignCriterion);
      operation.setOperator(Operator.ADD);
      operations.add(operation);
    }
    
    // Add a negative campaign criterion.
    Keyword negativeKeyword = new Keyword();
    negativeKeyword.setText("jupiter cruise");
    negativeKeyword.setMatchType(KeywordMatchType.BROAD);
    CampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
    negativeCriterion.setCampaignId(campaignId);
    negativeCriterion.setCriterion(negativeKeyword);

    CampaignCriterionOperation operation = new CampaignCriterionOperation();
    operation.setOperand(negativeCriterion);
    operation.setOperator(Operator.ADD);
    operations.add(operation);

    CampaignCriterionReturnValue result =
        campaignCriterionService.mutate(operations
            .toArray(new CampaignCriterionOperation[operations.size()]));

    // Display campaigns.
    for (CampaignCriterion campaignCriterion : result.getValue()) {
      System.out.printf("Campaign criterion with campaign ID %d, criterion ID %d, "
          + "and type '%s' was added.%n", campaignCriterion.getCampaignId(), campaignCriterion
          .getCriterion().getId(), campaignCriterion.getCriterion().getCriterionType());
    }
  }
}

Add demographic targeting critera to an ad group

// 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.targeting;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterion;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionOperation;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionReturnValue;
import com.google.api.ads.adwords.axis.v201705.cm.AdGroupCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.AgeRange;
import com.google.api.ads.adwords.axis.v201705.cm.BiddableAdGroupCriterion;
import com.google.api.ads.adwords.axis.v201705.cm.Gender;
import com.google.api.ads.adwords.axis.v201705.cm.NegativeAdGroupCriterion;
import com.google.api.ads.adwords.axis.v201705.cm.Operator;
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;

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

  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");

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    runExample(adWordsServices, session, adGroupId);
  }

  public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session, Long adGroupId)
      throws Exception {
    // Get the AdGroupCriterionService.
    AdGroupCriterionServiceInterface adGroupCriterionService =
        adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

    // https://developers.google.com/adwords/api/docs/appendix/genders
    Gender male = new Gender();
    male.setId(10L);
    BiddableAdGroupCriterion genderBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
    genderBiddableAdGroupCriterion.setAdGroupId(adGroupId);
    genderBiddableAdGroupCriterion.setCriterion(male);

    // https://developers.google.com/adwords/api/docs/appendix/ages
    AgeRange undetermined = new AgeRange();
    undetermined.setId(503999L);
    NegativeAdGroupCriterion ageRangeNegativeAdGroupCriterion = new NegativeAdGroupCriterion();
    ageRangeNegativeAdGroupCriterion.setAdGroupId(adGroupId);
    ageRangeNegativeAdGroupCriterion.setCriterion(undetermined);

    AdGroupCriterionOperation genderAdGroupCriterionOperation = new AdGroupCriterionOperation();
    genderAdGroupCriterionOperation.setOperand(genderBiddableAdGroupCriterion);
    genderAdGroupCriterionOperation.setOperator(Operator.ADD);
    AdGroupCriterionOperation ageRangeNegativeAdGroupCriterionOperation =
        new AdGroupCriterionOperation();
    ageRangeNegativeAdGroupCriterionOperation.setOperand(ageRangeNegativeAdGroupCriterion);
    ageRangeNegativeAdGroupCriterionOperation.setOperator(Operator.ADD);

    AdGroupCriterionReturnValue result =
        adGroupCriterionService.mutate(new AdGroupCriterionOperation[] {
            genderAdGroupCriterionOperation, ageRangeNegativeAdGroupCriterionOperation});

    // Display campaigns.
    for (AdGroupCriterion adGroupCriterion : result.getValue()) {
      System.out.printf("AdGroup criterion with adGroup ID %d, criterion ID %d, "
          + "and type '%s' was added.%n", adGroupCriterion.getAdGroupId(),
          adGroupCriterion.getCriterion().getId(),
          adGroupCriterion.getCriterion().getCriterionType());
    }
  }
}

Get all campaign targeting criteria

// 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.targeting;

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.CampaignCriterion;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterionPage;
import com.google.api.ads.adwords.axis.v201705.cm.CampaignCriterionServiceInterface;
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.CampaignCriterionField;
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 illustrates how to retrieve all the campaign criteria. To add
 * campaign criteria, run AddCampaignTargetingCriteria.java.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class GetCampaignTargetingCriteria {

  private static final int PAGE_SIZE = 100;

  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 CampaignService.
    CampaignCriterionServiceInterface campaignCriterionService =
        adWordsServices.get(session, CampaignCriterionServiceInterface.class);

    int offset = 0;

    // Create selector.
    SelectorBuilder builder = new SelectorBuilder();
    Selector selector = builder
        .fields(
            CampaignCriterionField.CampaignId,
            CampaignCriterionField.Id,
            CampaignCriterionField.CriteriaType,
            CampaignCriterionField.PlatformName,
            CampaignCriterionField.LanguageName,
            CampaignCriterionField.LocationName,
            CampaignCriterionField.KeywordText)
        .in(CampaignCriterionField.CriteriaType, "KEYWORD", "LANGUAGE", "LOCATION", "PLATFORM")
        .offset(0)
        .limit(PAGE_SIZE)
        .build();

    CampaignCriterionPage page = null;
    do {
      page = campaignCriterionService.get(selector);

      if (page.getEntries() != null) {
        // Display campaigns.
        for (CampaignCriterion campaignCriterion : page.getEntries()) {
          System.out.printf("Campaign criterion with campaign ID %d, criterion ID %d, "
              + "and type '%s' was found.%n", campaignCriterion.getCampaignId(), campaignCriterion
              .getCriterion().getId(), campaignCriterion.getCriterion().getCriterionType());
        }
        Thread.sleep(1000);
      } else {
        System.out.println("No campaign criteria were found.");
      }
      offset += PAGE_SIZE;
      selector = builder.increaseOffsetBy(PAGE_SIZE).build();
    } while (offset < page.getTotalNumEntries());
  }
}

Get all targetable languages and carriers

// 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.targeting;

import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201705.cm.Carrier;
import com.google.api.ads.adwords.axis.v201705.cm.ConstantDataServiceInterface;
import com.google.api.ads.adwords.axis.v201705.cm.Language;
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;

/**
 * This example illustrates how to retrieve all languages and carriers available
 * for targeting.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class GetTargetableLanguagesAndCarriers {

  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 ConstantDataService.
    ConstantDataServiceInterface constantDataService =
        adWordsServices.get(session, ConstantDataServiceInterface.class);

    // Get all carriers.
    Carrier[] carriers = constantDataService.getCarrierCriterion();

    // Display results.
    for (Carrier carrier : carriers) {
      System.out.printf("Carrier with name '%s', ID %d, and country code '%s' was found.%n",
          carrier.getName(), carrier.getId(), carrier.getCountryCode());
    }

    // Get all languages.
    Language[] languages = constantDataService.getLanguageCriterion();

    // Display results.
    for (Language language : languages) {
      System.out.printf("Language with name '%s' and ID %d was found.%n", language.getName(),
          language.getId());
    }
  }
}

Get location criteria by name

// 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.targeting;

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.Location;
import com.google.api.ads.adwords.axis.v201705.cm.LocationCriterion;
import com.google.api.ads.adwords.axis.v201705.cm.LocationCriterionServiceInterface;
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.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 location criteria by name.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the
 * "ads.properties" file. See README for more info.
 */
public class LookupLocation {

  /**
   * Helper function to format a string for parent locations.
   *
   * @param parents List of parent locations.
   * @return Formatted string representing parent locations.
   */
  public static String getParentLocationString(Location[] parents) {
    StringBuilder sb = new StringBuilder();
    if (parents != null) {
      for (Location parent : parents) {
        if (sb.length() > 0) {
          sb.append(", ");
        }
        sb.append(String.format("%s (%s)", parent.getLocationName(), parent.getDisplayType()));
      }
    } else {
      sb.append("N/A");
    }
    return sb.toString();
  }

  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();

    String[] locationNames = new String[] {"Paris", "Quebec", "Spain", "Deutschland"};

    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

    runExample(adWordsServices, session, locationNames);
  }

  public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session, String[] locationNames)
      throws Exception {
    // Get the LocationCriterionService.
    LocationCriterionServiceInterface locationCriterionService =
        adWordsServices.get(session, LocationCriterionServiceInterface.class);

    Selector selector = new SelectorBuilder()
        .fields(
            "Id",
            "LocationName",
            "CanonicalName",
            "DisplayType",
            "ParentLocations",
            "Reach",
            "TargetingStatus")
        // Location names must match exactly, only EQUALS and IN are supported.
        .in("LocationName", locationNames)
        // Set the locale of the returned location names.
        .equals("Locale", "en")
        .build();

    // Make the get request.
    LocationCriterion[] locationCriteria = locationCriterionService.get(selector);

    // Display the resulting location criteria.
    for (LocationCriterion locationCriterion : locationCriteria) {
      String parentString =
          getParentLocationString(locationCriterion.getLocation().getParentLocations());
      System.out.printf("The search term '%s' returned the location '%s (%d)' of type '%s' "
          + "with parent locations '%s' and reach %d (%s).%n", locationCriterion.getSearchTerm(),
          locationCriterion.getLocation().getLocationName(), locationCriterion.getLocation()
              .getId(), locationCriterion.getLocation().getDisplayType(), parentString,
          locationCriterion.getReach(), locationCriterion.getLocation().getTargetingStatus());
    }
  }
}

Send feedback about...

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