前向兼容性映射

借助 forwardCompatibilityMap 字段,您可以在一些最前沿的功能在 API 中正式公开之前先行研究它们。一些主要的 API 实体(例如 Campaign)中都包含了此字段。

forwardCompatibilityMap 属于 String_StringMapEntry 类型,表示字符串到字符串的映射。该映射用于获取和设置 API 实体的某些属性,即那些尚不可用作对象或其后代的正式属性的属性。这些属性通过 forwardCompatibilityMap 中的键加以公开。具有 forwardCompatibilityMap 字段的对象包括 CampaignAdGroupAdGroupAd

读取映射

您不需要将 forwardCompatibilityMap 字段引用为 Selector.fields 数组的一部分。如果您使用的 API 版本和服务中至少公开了一个键,则 forwardCompatibilityMap 字段将显示在响应中。

映射可包含一组键(每个对象类型对应一个键),这些键公开为对象或其后代之一的正式属性的扩展。对象的 forwardCompatibilityMap 中的键可能会引用该对象的后代的属性,而不是对象本身。例如,您可能会在 AdGroupAd 的映射中看到键 Ad.devicePreferred,但实际上,该键属于 Ad 对象(AdGroupAd 的后代)。

映射值的类型为 string,但根据相关键及其所表示的属性,这类值可以是其他基本数据类型(如整数或布尔值)的字符串表示形式。您可能需要先转换类型,然后再使用。

获取示例

以下是在 CampaignService 中调用 get() 方法的示例,该调用从各个广告系列的 forwardCompatibilityMap 中获取特定键的值。

Java

// Get the CampaignService.
CampaignServiceInterface campaignService =
    adWordsServices.get(session, CampaignServiceInterface.class);

// Create selector.
// Notice there is no need to explicitly request the
// forwardCompatibilityMap, indeed adding to the list of fields
// will throw an error.
SelectorBuilder selectorBuilder =
    new SelectorBuilder().fields(CampaignField.Id).limit(PAGE_SIZE);

int offset = 0;

CampaignPage page;
Map<Long, Boolean> campaignMap = new HashMap<>();
do {
  page = campaignService.get(selectorBuilder.build());

  // Collect the campaigns from the page.
  for (Campaign campaign : page.getEntries()) {
    Map<String, String> forwardCompatibilityMap =
        Maps.toMap(campaign.getForwardCompatibilityMap());
    String value = forwardCompatibilityMap.get(compatibilityMapKey);
    System.out.printf(
        "Campaign ID %d has forward compatibility map value of '%s' for key '%s'.%n",
        campaign.getId(), value, compatibilityMapKey);
    // This demonstrates how to handle a forward compatibility map key where
    // the value is a boolean. Check the forward compatibility map documentation
    // for the data type for each supported key:
    // https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
    campaignMap.put(campaign.getId(), value == null ? null : Boolean.valueOf(value));
  }
  offset += PAGE_SIZE;
  selectorBuilder.increaseOffsetBy(PAGE_SIZE);
} while (offset < page.getTotalNumEntries());
return campaignMap;

C#

// Get the CampaignService.
CampaignService campaignService = (CampaignService)user.GetService(
    AdWordsService.v201802.CampaignService);

// Create selector. There is no need to explicitly request the forwardCompatibilityMap field.
// Requesting this field through selectors will throw an error.
Selector selector = new Selector() {
  fields = new string[] { Campaign.Fields.Id },
  paging = Paging.Default
};

CampaignPage page = new CampaignPage();
Dictionary<long, bool> campaignMap = new Dictionary<long, bool>();

try {
  do {
    // Get the campaigns.
    page = campaignService.get(selector);

    // Display the results.
    if (page != null && page.entries != null) {
      foreach (Campaign campaign in page.entries) {
        Dictionary<String, String> forwardCompatibilityMap =
            campaign.forwardCompatibilityMap.ToDict();

        String value = CollectionUtilities.TryGetValue(
            forwardCompatibilityMap, compatibilityMapKey);

        if (value != null) {
          Console.WriteLine("Campaign ID {0} has forward compatibility map value of " +
              "'{1}' for key '{2}'.", campaign.id, compatibilityMapKey);
          // This demonstrates how to handle a forward compatibility map key where
          // the value is a boolean. Check the forward compatibility map documentation
          // for the data type for each supported key:
          // https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
          campaignMap[campaign.id] = Convert.ToBoolean(value);
        } else {
          campaignMap[campaign.id] = false;
        }
      }
    }
    selector.paging.IncreaseOffset();
  } while (selector.paging.startIndex < page.totalNumEntries);
  Console.WriteLine("Number of campaigns found: {0}", page.totalNumEntries);
} catch (Exception e) {
  throw new System.ApplicationException("Failed to retrieve forward compatibility map for " +
      "campaigns", e);
}
return campaignMap;

PHP

// Get the CampaignService.
$campaignService =
    $adWordsServices->get($session, CampaignService::class);

// Create selector.
// Notice there is no need to explicitly request the
// forwardCompatibilityMap, indeed adding to the list of fields
// will throw an error.
$selector = new Selector();
$selector->setFields(['Id']);
$selector->setPaging(new Paging(0, self::PAGE_LIMIT));

$campaignMap = [];
$foundResults = false;
do {
    // Retrieve campaigns one page at a time, continuing to request pages
    // until all campaigns have been retrieved.
    $page = $campaignService->get($selector);

    // Print out some information for each campaign.
    if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $campaign) {
            if (is_null($campaign->getForwardCompatibilityMap())) {
                continue;
            }
            $forwardCompatibilityMap = MapEntries::toAssociativeArray(
                $campaign->getForwardCompatibilityMap()
            );
            // This demonstrates how to handle a forward compatibility map key
            // where the value is a boolean. Check the forward compatibility map
            // documentation for the data type for each supported key:
            // https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
            $value =
                boolval($forwardCompatibilityMap[$compatibilityMapKey]);
            $foundResults = true;
            printf(
                "Campaign ID %d has forward compatibility map value of '%s' for "
                . "key '%s'.\n",
                $campaign->getId(),
                $value,
                $compatibilityMapKey
            );
            // Cast the ID to string to prevent 32-bit PHP to convert this to
            // negative number.
            $campaignId = strval($campaign->getId());
            $campaignMap[$campaignId] = $value;
        }
    }
    $selector->getPaging()->setStartIndex(
        $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT
    );
} while ($selector->getPaging()->getStartIndex() < $totalNumEntries);
if (!$foundResults) {
    print "No forward compatibility maps are found.\n";
}

return $campaignMap;

Python

# Get the CampaignService.
campaign_service = client.GetService('CampaignService', version='v201802')

# Create selector.
# Notice there is no need to explicitly request the forwardCompatibilityMap;
# adding to the list of fields will throw an error.
offset = 0
selector = {
    'fields': ['Id'],
    'paging': {
        'startIndex': offset,
        'numberResults': PAGE_SIZE
    }
}

campaign_map = {}
more_pages = True

while more_pages:
  page = campaign_service.get(selector)

  if 'entries' in page:
    for campaign in page['entries']:
      raw_fcm = getattr(
          campaign, 'forwardCompatibilityMap', {})
      forward_compatibility_map = {
          string_map_entry['key']: string_map_entry['value']
          for string_map_entry in raw_fcm
      }

      campaign_id = campaign['id']
      value = forward_compatibility_map.get(bool(compatibility_map_key),
                                            False)
      campaign_map[campaign_id] = value

      # This demonstrates how to handle a forward compatibility map key where
      # the value is a boolean. Check the forward compatibility map
      # documentation for the data type for each supported key:
      # https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
      print ('Campaign with id "%s" has forward compatibility map value of '
             '"%s" for key "%s".' % (campaign_id, value,
                                     compatibility_map_key))
  offset += PAGE_SIZE
  selector['paging']['startIndex'] = offset
  more_pages = offset < int(page['totalNumEntries'])

return campaign_map

Perl

# Create selector.
# Notice there is no need to explicitly request the forwardCompatibilityMap,
# indeed adding to the list of fields will throw an error.
my $paging = Google::Ads::AdWords::v201802::Paging->new({
  startIndex    => 0,
  numberResults => PAGE_SIZE
});
my $selector = Google::Ads::AdWords::v201802::Selector->new({
  fields     => ["Id"],
  paging     => $paging
});

my $campaign_map = {};
# Retrieve campaigns one page at a time, continuing to request pages until
# all campaigns have been retrieved.
Google::Ads::AdWords::Utilities::PageProcessor->new({
    client   => $client,
    service  => $client->CampaignService(),
    selector => $selector
  }
  )->process_entries(
  sub {
    # Print out some information for each campaign.
    my ($campaign) = @_;

    my $forward_compatibility_map =
        Google::Ads::Common::MapUtils::get_map(
          $campaign->get_forwardCompatibilityMap());
    if (defined $forward_compatibility_map) {
      # This demonstrates how to handle a forward compatibility map key
      # where the value is a boolean. Check the forward compatibility map
      # documentation for the data type for each supported key:
      # https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
      my $value = $forward_compatibility_map->{$compatibility_map_key};
      if (defined $value) {
        printf "Campaign ID %d has forward compatibility map value of '%s'" .
          " for key '%s'.\n", $campaign->get_id(), $value,
          $compatibility_map_key;
        $campaign_map->{$campaign->get_id()} = $value;
      }
    }
  });

if (!keys %{$campaign_map}) {
  print "No forward compatibility maps were found.\n";
}

return $campaign_map;

Ruby

# Create selector.
# Notice there is no need to explicitly request the forwardCompatibilityMap,
# indeed adding it to the list of fields will throw an error.
selector = {
  :fields => ['Id'],
  :paging => {
    :start_index => 0,
    :number_results => PAGE_SIZE
  }
}

campaign_map = {}

# Iterate over all pages.
offset, page = 0, {}
begin
  page = campaign_srv.get(selector)
  if page[:entries]
    page[:entries].each do |campaign|
      unless campaign[:forward_compatibility_map].nil?
        value = campaign[:forward_compatibility_map][fcm_key]
        unless value.nil?
          puts ("Campaign ID %d has forward compatibility map value of '%s'" +
             " for key '%s'") % [campaign[:id], fcm_key, value]
          # This demonstrates how to handle a forward compatibility map key
          # where the value is a boolean. Check the forward compatibility map
          # documentation for the data type for each supported key:
          # https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
          campaign_map[campaign[:id]] = (value.casecmp('true') >= 0)
        end
      end
    end
    # Increment values to request the next page.
    offset += PAGE_SIZE
    selector[:paging][:start_index] = offset
  end
end while page[:total_num_entries] > offset

return campaign_map

从映射中更改属性

通过 forwardCompatibilityMap 转变键与转变任何其他属性并无二致:您只需要调用 mutate() 方法,确保 forwardCompatibilityMap 中填充了您要更改的键和值。常规 ADDSET mutate 操作接受 forwardCompatibilityMap 数据,但可能需要一些配置。

务必为键传递有效的值,否则会产生 ApiException。另外,应确保使用正确的键名,因为使用错误或未定义的键名会被 API 忽略且不会发出相应的提示,从而可能导致难以诊断的错误。

Mutate 示例

以下示例演示如何通过在 forwardCompatibilityMap 中发送键和值来更改广告系列。

Java

// This is an example on how to update a campaign using the
// CampaignService and the forwardCompatibilityMap field.

// Get the CampaignService.
CampaignServiceInterface campaignService =
    adWordsServices.get(session, CampaignServiceInterface.class);

// Create campaign with updated status.
Campaign campaign = new Campaign();
campaign.setId(campaignId);
// Set the forward compatibility map entry to "true" to update the campaign.
// This demonstrates how to handle a forward compatibility map key where
// the value is a boolean. Check the forward compatibility map documentation
// for the data type for each supported key:
// https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
campaign.setForwardCompatibilityMap(
    new String_StringMapEntry[] {
      new String_StringMapEntry(compatibilityMapKey, Boolean.TRUE.toString())
    });

// Create operations.
CampaignOperation operation = new CampaignOperation();
operation.setOperand(campaign);
operation.setOperator(Operator.SET);

CampaignOperation[] operations = new CampaignOperation[] {operation};

// Update campaign.
CampaignReturnValue result = campaignService.mutate(operations);
System.out.printf(
    "Updated forward compatibility map of campaign ID %d.%n", result.getValue(0).getId());

C#

// This is an example on how to update a campaign using the
// CampaignService and the forwardCompatibilityMap field.

// Get the CampaignService.
CampaignService campaignService = (CampaignService)user.GetService(
    AdWordsService.v201802.CampaignService);

// Create campaign with updated status.
Campaign campaign = new Campaign();
campaign.id = campaignId;
// Set the forward compatibility map entry to "true" to update the campaign.
// This demonstrates how to handle a forward compatibility map key where
// the value is a boolean. Check the forward compatibility map documentation
// for the data type for each supported key:
// https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
campaign.forwardCompatibilityMap = new String_StringMapEntry[] {
  new String_StringMapEntry() {
    key = compatibilityMapKey,
    value = Boolean.TrueString
  }
};

// Create operations.
CampaignOperation operation = new CampaignOperation();
operation.operand = campaign;
operation.@operator = Operator.SET;

try {
  CampaignOperation[] operations = new CampaignOperation[] { operation };

  // Update campaign.
  CampaignReturnValue result = campaignService.mutate(operations);
  Console.WriteLine("Updated forward compatibility map of campaign ID {0}.",
      result.value[0].id);
} catch (Exception e) {
  throw new System.ApplicationException("Failed to update forward compatibility map for " +
      "campaigns", e);
}

PHP

// This is an example on how to update a campaign using the
// CampaignService and the forwardCompatibilityMap field.

// Get the CampaignService.
$campaignService =
    $adWordsServices->get($session, CampaignService::class);

// Create campaign with updated status.
$campaign = new Campaign();
$campaign->setId($campaignId);
// Set the forward compatibility map entry to "true" to update the campaign.
// This demonstrates how to handle a forward compatibility map key
// where the value is a boolean. Check the forward compatibility map
// documentation for the data type for each supported key:
// https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
$campaign->setForwardCompatibilityMap(
    [
        new String_StringMapEntry($compatibilityMapKey, 'true')
    ]
);

// Create operations.
$operation = new CampaignOperation();
$operation->setOperand($campaign);
$operation->setOperator(Operator::SET);

// Update campaign on the server.
$result = $campaignService->mutate([$operation]);
printf(
    "Updated forward compatibility map of campaign ID %d.\n",
    $result->getValue()[0]->getId()
);

Python

# This is an example on how to update a campaign using the CampaignService and
# the forwardCompatibilityMap field.

# Get the CampaignService.
campaign_service = client.GetService('CampaignService', version='v201802')

# Create campaign with updated status.
campaign = {
    'id': campaign_id,
    # This demonstrates how to handle a forward compatibility map key where
    # the value is a boolean. Check the forward compatibility map
    # documentation for the data type for each supported key:
    # https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
    'forwardCompatibilityMap': [{
        'key': compatibility_map_key,
        'value': str(True)
    }]
}

# Create operations.
operations = [{
    'operand': campaign,
    'operator': 'SET'
}]

# Update campaign.
updated_campaign = campaign_service.mutate(operations)['value'][0]
print 'Updated forward compatibility map of campaign ID "%d".' % (
    updated_campaign['id'])

Perl

# This is an example on how to update a campaign using the
# CampaignService and the forwardCompatibilityMap field.

# Create campaign with updated status.
my $campaign = Google::Ads::AdWords::v201802::Campaign->new({
  id => $campaign_id,
  # Set the forward compatibility map entry to "1" to update the campaign.
  # This demonstrates how to handle a forward compatibility map key
  # where the value is a boolean. Check the forward compatibility map
  # documentation for the data type for each supported key:
  # https://developers.google.com/adwords/api/docs/guides/forward-compatibility-maps
  forwardCompatibilityMap =>
    [Google::Ads::AdWords::v201802::String_StringMapEntry->new({
      key   => $compatibility_map_key,
      value => 1})]
});

my $operation = Google::Ads::AdWords::v201802::CampaignOperation->new({
  operand  => $campaign,
  operator => "SET"
});

# Update campaign on the server.
my $result = $client->CampaignService()->mutate({
  operations => [$operation]});

printf("Updated forward compatibility map of campaign ID %d.\n",
      $result->get_value()->[0]->get_id());

Ruby

# Prepare for updating campaign.
operation = {
  :operator => 'SET',
  :operand => {
    :id => campaign_id,
    # Set the forward compatibility map entry to "true" as an example.
    :forward_compatibility_map => [
      {:key => fcm_key, :value => true}
    ]
  }
}

# Update campaign.
response = campaign_srv.mutate([operation])
if response and response[:value]
  campaign = response[:value].first
  puts "Campaign ID %d was successfully updated." % campaign[:id]
else
  puts 'No campaigns were updated.'
end

处理错误

某些操作(例如在 forwardCompatibilityMap 中传递某个键的无效)会产生包含 ApiErrorApiException。该错误将包含指向 forwardCompatibilityMapfieldPath 以及填充了非法值的 trigger

传递无效的键名可能导致难以诊断的错误,因为 API 会允许传递该无效键名而不发出相关提示。

另外值得注意的是,键与具体的 API 版本相关联。对某个版本有效的键在其功能在 API 中正式实现后,将不再被未来的版本所接受。如果将某个键传递到不再接受它的 API 版本,将返回 ApiException

常见问题解答

如何请求在响应中填充 forwardCompatibilityMap?我在文档中没有看到它的字段名。

不必作为 Selector.fields 的一部分请求该字段,只要应返回到映射中的对象附加有数据,就会填充该字段。

为何未填充 forwardCompatibilityMap

一般来说是因为对象中没有任何数据附加到您期望在映射中看到的键。

如果在映射中发送了错误的键,会收到错误吗?

不会,在指定键的名称时要小心,因为 API 会在不发出提示的情况下忽略无法识别的键。

我知道对象中有受支持的新字段/键,但是该对象似乎没有 forwardCompatibilityMap

只有最高一级的 API 实体(比如 CampaignAdGroupAdGroupAd)才可公开 forwardCompatibilityMap。但是,有些键会影响底层对象。

如果在映射中发送了错误的值,会发生什么情况?

如果您设置了正确的键,但使用了不受支持的值,将返回 ApiException

键会在所有 API 版本中都公开吗?

不会,只有在尚未公开此功能的 API 版本中才会公开和接受键。

当前的 ForwardCompatibilityMap 键

可用的 ForwardCompatibilityMap 键
服务
AdGroupAdService
实体
AdGroupAd
键名
Ad.type
选择器字段
AdType
类型
枚举
支持的版本
v201710、v201802
只读

如果 ExpandedTextAd广告变体,则将其设置为 AD_VARIATION。对于所有其他广告类型以及不是广告变体的 ExpandedTextAd,前向兼容性映射中都不存在该键。

v201802 中引入了检测广告变体这一功能。您可以使用此字段检测早期 API 版本中的广告变体。

发送以下问题的反馈:

此网页
AdWords API
AdWords API
需要帮助?请访问我们的支持页面