라벨

라벨을 사용하면 캠페인, 광고 그룹, 광고, 키워드를 분류하고 해당 카테고리를 사용해 다양한 방식으로 워크플로를 간소화할 수 있습니다.

이 가이드에서는 다음을 수행하는 데 필요한 단계를 설명합니다.

  • LabelService를 사용하여 프로그래매틱 방식으로 라벨을 만듭니다.
  • CampaignLabelService 요청을 사용하여 캠페인에 라벨을 할당합니다.
  • GoogleAdsService 쿼리를 사용하여 라벨별로 보고서 결과를 검색하고 필터링합니다.

이 가이드에서는 캠페인을 중점적으로 설명하지만 광고그룹, 광고, 키워드에 동일한 방법을 사용할 수 있습니다. API는 관리자 계정이 하위 계정에 라벨을 할당할 수 있는 CustomerLabelService도 제공합니다.

사용 사례

라벨을 사용하는 일반적인 시나리오는 다음과 같습니다.

  • 계정에 일 년 중 특정 기간에만 사용 설정하는 캠페인이 있으며, 이러한 캠페인을 보고서에 쉽게 포함하거나 제외하려는 경우
  • 광고그룹에 새 키워드 세트를 추가했는데 이 통계를 광고그룹의 다른 키워드와 비교하려고 합니다.
  • Google Ads 계정의 사용자는 각각 캠페인의 하위 집합을 관리하며, 각 사용자에 대한 캠페인 집합을 식별하고 싶습니다.
  • 앱은 특정 객체의 상태를 표시해야 합니다.

라벨 만들기

TextLabel 객체로 라벨을 만듭니다.

  1. TextLabel 인스턴스를 생성합니다.
  2. TextLabel의 배경 색상을 설정합니다.
  3. 설명 입력란을 사용하여 이 TextLabel의 텍스트를 입력합니다.
  4. TextLabelLabelOperation에 래핑하여 LabelService.MutateLabels로 전송합니다.

이후 쿼리를 위해 새 라벨 ID를 기록해 둡니다. ID는 MutateLabelsResponse에 반환된 MutateLabelResultsresource_name 필드에 삽입됩니다.

LabelService.GetLabel 요청이나 GoogleAdsService Search 또는 SearchStream 요청을 사용하여 ID를 검색할 수도 있습니다.

라벨 할당

라벨을 캠페인, 고객, 광고그룹, 기준 또는 광고에 지정할 수 있습니다. 적절한 서비스에서 Mutate 작업을 사용하여 라벨을 할당합니다.

예를 들어 캠페인에 라벨을 할당하려면 하나 이상의 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.V16.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;
    }
}
      

2,399필리핀

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

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

라벨을 사용하여 객체 검색

캠페인에 라벨을 할당한 후 라벨 필드를 사용하여 ID별로 객체를 검색할 수 있습니다.

적절한 GAQL 쿼리를 GoogleAdsService Search 또는 SearchStream 요청에 전달합니다. 예를 들어 다음 쿼리는 세 가지 라벨 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"

고객에게 적용된 라벨을 가져옵니다.

관리자 계정의 계정 계층 구조를 가져올 때 CustomerClient 객체에서 applied_labels 필드를 요청하여 하위 고객 계정에 적용된 라벨 목록을 가져올 수 있습니다. 이 필드는 API를 호출하는 고객이 소유한 라벨만 검색합니다.

보고서에서 라벨 사용하기

라벨 보고

라벨 보고서 리소스는 계정에 정의된 라벨에 대한 세부정보를 반환합니다. 세부정보에는 이름, ID, 리소스 이름, 상태, 배경 색상, 설명은 물론 라벨 소유자를 나타내는 고객 리소스가 포함됩니다.

측정항목이 포함된 보고서

광고그룹캠페인 보고서 보기에 labels 필드가 표시됩니다. 보고 서비스는 customers/{customer_id}/labels/{label_id} 형식으로 라벨 리소스 이름을 반환합니다. 예를 들어 리소스 이름 customers/123456789/labels/012345는 ID가 123456789인 계정에서 ID가 012345인 라벨을 참조합니다.

측정항목이 없는 보고서

다음 각 보고서 리소스는 리소스와 라벨 간의 관계를 찾는 데 사용할 수 있습니다.

숫자 비교 연산자 또는 BETWEEN, IS NULL, IS NOT NULL, IN, NOT IN 연산자를 사용하여 label.id 필드를 비교하여 위의 보고서 결과를 필터링할 수 있습니다.

예를 들어 다음과 같이 특정 라벨 ID를 가진 모든 캠페인을 가져올 수 있습니다.

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