ラベル

ラベルを使用すると、キャンペーン、広告グループ、広告、キーワードを分類し、その分類を使用してさまざまな方法でワークフローを簡素化できます。

このガイドでは以下の作業の手順を紹介します。

  • プログラムでラベルを作成する LabelService
  • CampaignLabelService リクエストを使用してキャンペーンにラベルを割り当てる。
  • GoogleAdsService クエリを使用して、ラベルでレポート結果を取得してフィルタする。

このガイドではキャンペーンに焦点を当てていますが、広告グループ、広告、キーワードにも同じアプローチを使用できます。この API には CustomerLabelServiceも用意されています。これにより、 クライアント センター(MCC)アカウントは子アカウントにラベルを割り当てることができます。

ユースケース

ラベルを使用する一般的なシナリオは次のとおりです。

  • アカウントに、1 年の特定の期間にのみ有効にするキャンペーンがあり、それらのキャンペーンをレポートに含めるか除外するかを切り替えたい。
  • 広告グループに新しいキーワードのセットを追加し、その統計情報を広告グループ内の他のキーワードと比較したい。
  • Google 広告アカウントのユーザーがそれぞれキャンペーンのサブセットを管理しており、各ユーザーのキャンペーンのセットを識別する方法が必要である。
  • アプリで特定のオブジェクトのステータスをマークする必要がある。

ラベルを作成する

TextLabel オブジェクトを使用してラベルを作成します。

  1. TextLabel インスタンスを作成します。
  2. この TextLabel の背景色を設定します。
  3. 説明フィールドを使用して、この TextLabel のテキストを入力します。
  4. TextLabelLabelOperation でラップし、 LabelService.MutateLabels に送信します。

後でクエリを実行するために、新しいラベルの ID をメモしておきます。ID は、 MutateLabelsResponse で返される MutateLabelResultsresource_name フィールドに埋め込まれています。

ID を取得するには、GoogleAdsService Search または SearchStream リクエストを使用します。

ラベルの割り当て

キャンペーン、顧客、広告グループ、条件、広告にラベルを割り当てることができます。 ラベルを割り当てるには、適切なサービスの Mutate オペレーションを使用します。

たとえば、キャンペーンにラベルを割り当てるには、1 つ以上の CampaignLabelOperationCampaignLabelService.MutateCampaignLabels に渡します。 各 CampaignLabelOperation には CampaignLabel インスタンスが含まれます。このインスタンスには次の フィールドが含まれます。

  • label: ラベルの ID
  • campaign: キャンペーンの ID

ラベルとキャンペーンのペアごとに CampaignLabel インスタンスを作成します。create オペレーションを使用して CampaignLabelOperation でラップし、CampaignService.MutateCampaignLabels に送信します。

キャンペーン ラベルの追加

キャンペーンのリストにキャンペーン ラベルを追加する方法を示すコード例を次に示します。

Java

private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, List<Long> campaignIds, Long labelId) {
  // Gets the resource name of the label to be added across all given campaigns.
  String labelResourceName = ResourceNames.label(customerId, labelId);

  List<CampaignLabelOperation> operations = new ArrayList<>(campaignIds.size());
  // Creates a campaign label operation for each campaign.
  for (Long campaignId : campaignIds) {
    // Gets the resource name of the given campaign.
    String campaignResourceName = ResourceNames.campaign(customerId, campaignId);
    // Creates the campaign label.
    CampaignLabel campaignLabel =
        CampaignLabel.newBuilder()
            .setCampaign(campaignResourceName)
            .setLabel(labelResourceName)
            .build();

    operations.add(CampaignLabelOperation.newBuilder().setCreate(campaignLabel).build());
  }

  try (CampaignLabelServiceClient campaignLabelServiceClient =
      googleAdsClient.getLatestVersion().createCampaignLabelServiceClient()) {
    MutateCampaignLabelsResponse response =
        campaignLabelServiceClient.mutateCampaignLabels(Long.toString(customerId), operations);
    System.out.printf("Added %d campaign labels:%n", response.getResultsCount());
    for (MutateCampaignLabelResult result : response.getResultsList()) {
      System.out.println(result.getResourceName());
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId, long[] campaignIds, long labelId)
{
    // Get the CampaignLabelServiceClient.
    CampaignLabelServiceClient campaignLabelService =
        client.GetService(Services.V24.CampaignLabelService);

    // Gets the resource name of the label to be added across all given campaigns.
    string labelResourceName = ResourceNames.Label(customerId, labelId);

    List<CampaignLabelOperation> operations = new List<CampaignLabelOperation>();
    // Creates a campaign label operation for each campaign.
    foreach (long campaignId in campaignIds)
    {
        // Gets the resource name of the given campaign.
        string campaignResourceName = ResourceNames.Campaign(customerId, campaignId);
        // Creates the campaign label.
        CampaignLabel campaignLabel = new CampaignLabel()
        {
            Campaign = campaignResourceName,
            Label = labelResourceName
        };

        operations.Add(new CampaignLabelOperation()
        {
            Create = campaignLabel
        });
    }

    // Send the operation in a mutate request.
    try
    {
        MutateCampaignLabelsResponse response =
            campaignLabelService.MutateCampaignLabels(customerId.ToString(), operations);
        Console.WriteLine($"Added {response.Results} campaign labels:");

        foreach (MutateCampaignLabelResult result in response.Results)
        {
            Console.WriteLine(result.ResourceName);
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    array $campaignIds,
    int $labelId
) {
    // Gets the resource name of the label to be added across all given campaigns.
    $labelResourceName = ResourceNames::forLabel($customerId, $labelId);

    // Creates a campaign label operation for each campaign.
    $operations = [];
    foreach ($campaignIds as $campaignId) {
        // Creates the campaign label.
        $campaignLabel = new CampaignLabel([
            'campaign' => ResourceNames::forCampaign($customerId, $campaignId),
            'label' => $labelResourceName
        ]);
        $campaignLabelOperation = new CampaignLabelOperation();
        $campaignLabelOperation->setCreate($campaignLabel);
        $operations[] = $campaignLabelOperation;
    }

    // Issues a mutate request to add the labels to the campaigns.
    $campaignLabelServiceClient = $googleAdsClient->getCampaignLabelServiceClient();
    $response = $campaignLabelServiceClient->mutateCampaignLabels(
        MutateCampaignLabelsRequest::build($customerId, $operations)
    );

    printf("Added %d campaign labels:%s", $response->getResults()->count(), PHP_EOL);

    foreach ($response->getResults() as $addedCampaignLabel) {
        /** @var CampaignLabel $addedCampaignLabel */
        printf(
            "New campaign label added with resource name: '%s'.%s",
            $addedCampaignLabel->getResourceName(),
            PHP_EOL
        );
    }
}
      

Python

def main(
    client: GoogleAdsClient,
    customer_id: str,
    label_id: str,
    campaign_ids: List[str],
) -> None:
    """This code example adds a campaign label to a list of campaigns.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: A client customer ID str.
        label_id: The ID of the label to attach to campaigns.
        campaign_ids: A list of campaign IDs to which the label will be added.
    """

    # Get an instance of CampaignLabelService client.
    campaign_label_service: CampaignLabelServiceClient = client.get_service(
        "CampaignLabelService"
    )
    campaign_service: CampaignServiceClient = client.get_service(
        "CampaignService"
    )
    label_service: LabelServiceClient = client.get_service("LabelService")

    # Build the resource name of the label to be added across the campaigns.
    label_resource_name: str = label_service.label_path(customer_id, label_id)

    operations: List[Any] = []

    for campaign_id in campaign_ids:
        campaign_resource_name: str = campaign_service.campaign_path(
            customer_id, campaign_id
        )
        campaign_label_operation: Any = client.get_type(
            "CampaignLabelOperation"
        )

        campaign_label: CampaignLabel = campaign_label_operation.create
        campaign_label.campaign = campaign_resource_name
        campaign_label.label = label_resource_name
        operations.append(campaign_label_operation)

    response: MutateCampaignLabelsResponse = (
        campaign_label_service.mutate_campaign_labels(
            customer_id=customer_id, operations=operations
        )
    )
    print(f"Added {len(response.results)} campaign labels:")
    for result in response.results:
        print(result.resource_name)
      

Ruby

def add_campaign_label(customer_id, label_id, campaign_ids)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  label_resource_name = client.path.label(customer_id, label_id)

  labels = campaign_ids.map { |campaign_id|
    client.resource.campaign_label do |label|
      campaign_resource_name = client.path.campaign(customer_id, campaign_id)
      label.campaign = campaign_resource_name
      label.label = label_resource_name
    end
  }

  ops = labels.map { |label|
    client.operation.create_resource.campaign_label(label)
  }

  response = client.service.campaign_label.mutate_campaign_labels(
    customer_id: customer_id,
    operations: ops,
  )
  response.results.each do |result|
    puts("Created campaign label with id: #{result.resource_name}")
  end
end
      

Perl

sub add_campaign_labels {
  my ($api_client, $customer_id, $campaign_ids, $label_id) = @_;

  my $label_resource_name =
    Google::Ads::GoogleAds::V24::Utils::ResourceNames::label($customer_id,
    $label_id);

  my $campaign_label_operations = [];

  # Create a campaign label operation for each campaign.
  foreach my $campaign_id (@$campaign_ids) {
    # Create a campaign label.
    my $campaign_label =
      Google::Ads::GoogleAds::V24::Resources::CampaignLabel->new({
        campaign => Google::Ads::GoogleAds::V24::Utils::ResourceNames::campaign(
          $customer_id, $campaign_id
        ),
        label => $label_resource_name
      });

    # Create a campaign label operation.
    my $campaign_label_operation =
      Google::Ads::GoogleAds::V24::Services::CampaignLabelService::CampaignLabelOperation
      ->new({
        create => $campaign_label
      });

    push @$campaign_label_operations, $campaign_label_operation;
  }

  # Add the campaign labels to the campaigns.
  my $campaign_labels_response = $api_client->CampaignLabelService()->mutate({
    customerId => $customer_id,
    operations => $campaign_label_operations
  });

  my $campaign_label_results = $campaign_labels_response->{results};
  printf "Added %d campaign labels:\n", scalar @$campaign_label_results;

  foreach my $campaign_label_result (@$campaign_label_results) {
    printf "Created campaign label '%s'.\n",
      $campaign_label_result->{resourceName};
  }

  return 1;
}
      

curl

顧客にラベルを割り当てる

顧客にラベルを割り当てることは、クライアント センター(MCC)アカウントがクライアント アカウントを分類する一般的なタスクです。これは CustomerLabelServiceを使用して行います。

CustomerLabelOperation には CustomerLabel インスタンスが含まれます。新しい関係を作成する際は、次の点に注意してください。

  • label:このフィールドは必須であり、クライアント センター(MCC)アカウントが所有するラベル のリソース名である必要があります。たとえば、 customers/{MANAGER_ID}/labels/{LABEL_ID} のようになります。
  • customer: このフィールドは出力専用であり、リクエストで設定しないでください。ラベル付けされる顧客は、MutateCustomerLabelsRequest パスの customer_id によって決まります。

ラベルを使ってオブジェクトを取得する

キャンペーンにラベルを割り当てたら、ラベル フィールドを使用して ID でオブジェクトを取得できます。

適切な GAQL クエリを GoogleAdsService Search または SearchStream リクエストに渡します。たとえば、次のクエリは、3 つのラベル ID のいずれかに関連付けられた各キャンペーンの ID、名前、ラベルを返します。

SELECT
  campaign.id,
  campaign.name,
  label.id,
  label.name
FROM campaign_label
WHERE label.id IN (123456, 789012, 345678)

フィルタできるのはラベル ID のみで、ラベル名はフィルタできません。ラベル名からラベル ID を取得するには、次のクエリを使用します。

SELECT
  label.id,
  label.name
FROM label
WHERE label.name = "LABEL_NAME"

顧客に適用されたラベルを取得する

クライアント センター(MCC)アカウント配下のアカウントの階層を取得するときに、 子顧客アカウントに適用されたラベルのリストを取得できます。これを行うには、 applied_labels フィールドを CustomerClient オブジェクトからリクエストします。このフィールドは、API 呼び出しを行う顧客が所有するラベルのみを取得します。

レポートでラベルを使用する

ラベルを使用して、レポートの有用性を高めます。

ラベルのレポート

ラベル レポート リソースは、アカウントで定義されたラベル の詳細を返します。詳細には、名前、ID、リソース名、ステータス、 背景色、説明のほか、ラベルの所有者を表す顧客 リソースが含まれます。

指標を含むレポート

広告グループ レポートと キャンペーン レポートの ビューには labels フィールドが含まれています。レポート サービスは、ラベルのリソース名を customers/{customer_id}/labels/{label_id} の形式で返します。たとえば、リソース名 customers/123456789/labels/012345 は、ID が 123456789 のアカウントの ID が 012345 のラベルを参照します。

指標を含まないレポート

次のレポート リソースを使用して、リソースとラベルの関係を確認できます。

これらのレポート結果をフィルタするには、label.id フィールドを 任意の数値比較演算子または BETWEENIS NULLIS NOT NULLINNOT IN 演算子を使用して比較します。

この例では、特定のラベル ID を持つすべてのキャンペーンを取得できます。

SELECT
  campaign.id,
  campaign.name,
  label.id,
  label.name
FROM campaign_label
WHERE label.id = LABEL_ID
ORDER BY campaign.id