ラベル

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

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

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

このガイドでは主にキャンペーンについて説明しますが、広告グループ、広告、キーワードについても同じ方法を使用できます。なお、API の CustomerLabelService を使用すると、MCC アカウントで子アカウントにラベルを割り当てることができます。

ユースケース

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

  • 特定の年にしか有効にしていないキャンペーンがあるアカウントで、そのキャンペーンをレポートに含めるか、レポートから除外したい。
  • 広告グループに新しいキーワード セットを追加し、その統計情報を広告グループの他のキーワードと比較したい。
  • Google 広告アカウントのユーザーは、それぞれが一部のキャンペーンを管理するため、各ユーザーのキャンペーン セットを簡単に特定できるようにする必要があります。
  • アプリケーションで、特定のオブジェクトのステータスを処理済み、監査済み、ハイライト表示などとしてマークする必要があります。

詳細と Google 広告でのラベルの仕組みの例については、ラベルの使用に関するヘルプセンター記事をご覧ください。

ラベルを作成する

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

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

以降のステップでは、新しいラベルの ID が必要になります。これらは、MutateLabelsResponse で返される MutateLabelResultsresource_name フィールドに埋め込まれます。または、LabelService.GetLabel リクエスト、GoogleAdsService SearchSearchStream リクエストを使用して ID を取得します。

ラベルの割り当て

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

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

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

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

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

キャンペーンにラベルを割り当てたら、ラベル フィールドを使用して、1 つ以上の特定のラベルを持つオブジェクトを取得できます。これを行うには、適切な 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 でフィルタリングしてください。

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

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

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

ラベルのレポート

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

指標を含むレポート

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

指標のないレポート

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

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

コードの例

クライアント ライブラリの [Campaign Management] フォルダには、キャンペーンにラベルを追加してラベルでキャンペーンを取得するコードサンプルが含まれています。

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

この例では、キャンペーンのリストにキャンペーン ラベルを追加する方法を示します。

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.V13.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(
        $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, customer_id, label_id, campaign_ids):
    """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 = client.get_service("CampaignLabelService")
    campaign_service = client.get_service("CampaignService")
    label_service = client.get_service("LabelService")

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

    operations = []

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

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

    response = 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::V13::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::V13::Resources::CampaignLabel->new({
        campaign => Google::Ads::GoogleAds::V13::Utils::ResourceNames::campaign(
          $customer_id, $campaign_id
        ),
        label => $label_resource_name
      });

    # Create a campaign label operation.
    my $campaign_label_operation =
      Google::Ads::GoogleAds::V13::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;
}
      

ラベルに基づくキャンペーンの取得

次の例では、特定のラベルが設定されたすべてのキャンペーンを取得する方法を示します。

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId, long labelId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    // Creates a request that will retrieve all campaign labels with the specified
    // labelId using pages of the specified page size.
    SearchGoogleAdsRequest request =
        SearchGoogleAdsRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setPageSize(PAGE_SIZE)
            .setQuery(
                "SELECT campaign.id, campaign.name, label.id, label.name "
                    + "FROM campaign_label WHERE label.id = "
                    + labelId
                    + " ORDER BY campaign.id")
            .build();
    // Issues the search request.
    SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);
    // Checks if the total results count is greater than 0.
    if (searchPagedResponse.getPage().getResponse().getTotalResultsCount() > 0) {
      // Iterates over all rows in all pages and prints the requested field values for the
      // campaigns and labels in each row. The results include the campaign and label
      // objects because these were included in the search criteria.
      for (GoogleAdsRow googleAdsRow : searchPagedResponse.iterateAll()) {
        System.out.printf(
            "Campaign found with name '%s', ID %d, and label: %s.%n",
            googleAdsRow.getCampaign().getName(),
            googleAdsRow.getCampaign().getId(),
            googleAdsRow.getLabel().getName());
      }
    } else {
      System.out.println("No campaigns were found.");
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId, long labelId)
{
    // Get the GoogleAdsServiceClient.
    GoogleAdsServiceClient googleAdsService =
        client.GetService(Services.V13.GoogleAdsService);

    // Creates a request that will retrieve all campaign labels with the specified
    // labelId using pages of the specified page size.
    SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
    {
        CustomerId = customerId.ToString(),
        Query = "SELECT campaign.id, campaign.name, label.id, label.name " +
            $"FROM campaign_label WHERE label.id = {labelId} ORDER BY campaign.id",
    };

    try
    {
        int count = 0;
        // Issues the search request and prints the result.
        foreach (GoogleAdsRow googleAdsRow in googleAdsService.Search(request))
        {
            count++;
            Console.WriteLine($"Campaign found with name '{googleAdsRow.Campaign.Name}'" +
                $", ID {googleAdsRow.Campaign.Id}, and label: " +
                $"'${googleAdsRow.Label.Name}'.");
        }
        if (count == 0)
        {
            Console.WriteLine("No campaigns were found.");
        }
    }
    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,
    int $labelId
) {
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    // Creates a query that will retrieve all campaign labels with the specified
    // label ID.
    $query = "SELECT campaign.id, campaign.name, label.id, label.name " .
        "FROM campaign_label WHERE label.id = $labelId ORDER BY campaign.id";
    // Issues a search request by specifying page size.
    $response =
        $googleAdsServiceClient->search($customerId, $query, ['pageSize' => self::PAGE_SIZE]);

    // Iterates over all rows in all pages and prints the requested field values for the
    // campaigns and labels in each row. The results include the campaign and label
    // objects because these were included in the search criteria.
    foreach ($response->iterateAllElements() as $googleAdsRow) {
        /** @var GoogleAdsRow $googleAdsRow */
        printf(
            "Campaign found with name '%s', ID %d, and label: '%s'.%s",
            $googleAdsRow->getCampaign()->getName(),
            $googleAdsRow->getCampaign()->getId(),
            $googleAdsRow->getLabel()->getName(),
            PHP_EOL
        );
    }
}
      

Python

def main(client, customer_id, label_id, page_size):
    """Demonstrates how to retrieve all campaigns by a given label ID.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: A client customer ID str.
        label_id: A label ID to use when searching for campaigns.
        page_size: An int of the number of results to include in each page of
            results.
    """
    ga_service = client.get_service("GoogleAdsService")

    # Creates a query that will retrieve all campaign labels with the
    # specified label ID.
    query = f"""
        SELECT
            campaign.id,
            campaign.name,
            label.id,
            label.name
         FROM campaign_label
         WHERE label.id = "{label_id}"
         ORDER BY campaign.id"""

    # Retrieves a google.api_core.page_iterator.GRPCIterator instance
    # initialized with the specified request parameters.
    request = client.get_type("SearchGoogleAdsRequest")
    request.customer_id = customer_id
    request.query = query
    request.page_size = page_size

    iterator = ga_service.search(request=request)

    # Iterates over all rows in all pages and prints the requested field
    # values for the campaigns and labels in each row. The results include
    # the campaign and label objects because these were included in the
    # search criteria.
    for row in iterator:
        print(
            f'Campaign found with ID "{row.campaign.id}", name '
            f'"{row.campaign.name}", and label "{row.label.name}".'
        )


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v13")

    parser = argparse.ArgumentParser(
        description="Lists all campaigns for specified customer."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    parser.add_argument(
        "-l",
        "--label_id",
        type=str,
        required=True,
        help="A label ID associated with a campaign.",
    )
    args = parser.parse_args()

    try:
        main(
            googleads_client,
            args.customer_id,
            args.label_id,
            _DEFAULT_PAGE_SIZE,
        )
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Ruby

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

  query = <<~EOQUERY
    SELECT campaign.id, campaign.name, label.id, label.name
    FROM campaign_label WHERE label.id = '#{label_id}' ORDER BY campaign.id
  EOQUERY

  ga_service = client.service.google_ads
  response = ga_service.search(
    customer_id: customer_id,
    query: query,
    page_size: PAGE_SIZE,
  )

  response.each do |row|
    puts "Campaign with ID #{row.campaign.id} and name '#{row.campaign.name}' was found."
  end
end
      

Perl

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

  # Create the search query.
  my $search_query =
    "SELECT campaign.id, campaign.name, label.id, label.name " .
    "FROM campaign_label WHERE label.id = $label_id ORDER BY campaign.id";

  # Create a search Google Ads request that will retrieve all campaign labels
  # with the specified label Id using pages of the specified page size.
  my $search_request =
    Google::Ads::GoogleAds::V13::Services::GoogleAdsService::SearchGoogleAdsRequest
    ->new({
      customerId => $customer_id,
      query      => $search_query,
      pageSize   => PAGE_SIZE
    });

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $iterator = Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator->new({
    service => $google_ads_service,
    request => $search_request
  });

  # Iterate over all rows in all pages and print the requested field values for the
  # campaigns and labels in each row. The results include the campaign and label
  # objects because these were included in the search criteria.
  while ($iterator->has_next) {
    my $google_ads_row = $iterator->next;

    printf "Campaign found with name '%s', ID %d, and label: '%s'.\n",
      $google_ads_row->{campaign}{name}, $google_ads_row->{campaign}{id},
      $google_ads_row->{label}{name};
  }

  return 1;
}