上位互換性マップ

forwardCompatibilityMap フィールドを使用すると、API で正式に公開される前の新しい機能を試すことができます。このフィールドは主要な API エンティティ(Campaign など)に含まれています。

String_StringMapEntry タイプの forwardCompatibilityMap は文字列と文字列の対応を表すもので、API エンティティのプロパティ(オブジェクトやその派生要素の正式な属性としてまだ公開されていないもの)を取得、設定するために使います。そうしたプロパティは forwardCompatibilityMap のキーを通じて公開されます。forwardCompatibilityMap フィールドを持つオブジェクトには CampaignAdGroupAdGroupAd があります。

マップを参照する

forwardCompatibilityMap フィールドを Selector.fields 配列の一部として参照する必要はありません。API のご利用のバージョンやサービスで少なくとも 1 つのキーが公開されていれば、forwardCompatibilityMap フィールドはレスポンスに含まれています。

マップにはオブジェクト タイプに応じた一連のキーが含まれ、オブジェクトやその派生要素の正式な属性の拡張機能として公開されます。オブジェクトの forwardCompatibilityMap に含まれるキーは、そのオブジェクトの属性ではなく派生要素の属性を参照している場合もあります。たとえば AdGroupAd のマップには Ad.devicePreferred というキーがありますが、このキーは実際には Ad オブジェクト(AdGroupAd の派生要素)のものです。

マップの値は string 型になりますが、関連するキーやそのキーが表す属性によっては、それらの値は別の基本的なデータ型(integer や boolean など)を文字列で表したものになる場合があります。そうしたデータ型は、場合により使用前に変換する必要があります。

サンプルを確認する

次のコードサンプルは 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 を使ってキーを変更する方法は、他の属性の場合と同じです。変更を加えるキーと値を forwardCompatibilityMap に設定して、mutate() メソッドを呼び出してください。通常の mutate オペレーション ADDSETforwardCompatibilityMap のデータを受け入れますが、次の点に注意してください。

キーに有効な値を指定しないと、ApiException が送出されます。また、キーの名前を間違えないようにすることも重要です。名前が不正確か未定義のキーは暗黙的に無視されるため、エラーの診断が難しくなります。

コードのサンプル

次のサンプルは、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 のキーとして無効なを渡した場合は、ApiError を含む ApiException が送出されます。このエラーには forwardCompatibilityMap を指す fieldPath と問題の値が入った trigger が含まれます。

無効なキー名を渡すと API で暗黙的に無視されるため、エラーの原因を調べることが難しくなります。

また、キーは API のバージョンに依存しますのでご注意ください。あるバージョンで有効だったキーでも、その機能が正式に導入されたバージョンでは使えなくなります。新しい API バージョンに、すでに使えなくなったキーを渡すと ApiException が返されます。

よくある質問

レスポンスに入力する forwardCompatibilityMap をリクエストする方法を教えてください。ドキュメントには該当するフィールド名が見当たりません。

このフィールドを Selector.fields でリクエストする必要はありません。マップで返されるオブジェクトにデータがあった場合に、自動的に入力されます。

forwardCompatibilityMap にデータが入力されないのはなぜですか?

一般的には、そのオブジェクトにマップのキーに関するデータがないためです。

マップに間違ったキーを送るとエラーになりますか?

いいえ。API は認識できないキーを暗黙的に無視するため、キー名を指定する際には間違えないようご注意ください。

オブジェクトに新しいフィールドやキーはありますが、forwardCompatibilityMap は見当たりません。

forwardCompatibilityMap は、API の上位レベルのエンティティ(CampaignAdGroupAdGroupAd など)でのみ公開されます。ただし、一部のキーは下位レベルのオブジェクトにも影響します。

マップに間違った値を送るとどうなりますか?

正しいキーを設定したうえで非対応の値を使うと、ApiException が返されます。

キーは API のすべてのバージョンで公開されますか?

いいえ。キーはその機能がまだ公開されていない API バージョンでのみ公開され、使用できます。

現在の ForwardCompatibilityMap キー

利用可能な ForwardCompatibilityMap キー
サービス
AdGroupAdService
エンティティ
AdGroupAd
キーの名前
Ad.type
セレクタ フィールド
AdType
Enum
サポートされているバージョン
v201710、v201802
読み取り専用

ExpandedTextAd広告バリエーションである場合は、AD_VARIATION に設定します。 他のタイプの広告の場合、広告バリエーションではない ExpandedTextAd の場合と同様に、このキーは上位互換性マップには含まれません。

広告バリエーションを検出する機能は v201802 で導入されました。 以前の API バージョンの広告バリエーションを検出するには、このフィールドを使用します。

フィードバックを送信...

ご不明な点がありましたら、Google のサポートページをご覧ください。