Nhãn

Nhãn giúp bạn phân loại chiến dịch, nhóm quảng cáo, quảng cáo và từ khoá, đồng thời sử dụng các danh mục đó để đơn giản hoá quy trình làm việc theo nhiều cách.

Hướng dẫn này trình bày các bước cần thiết để thực hiện những việc sau:

  • Tạo nhãn theo phương thức lập trình bằng LabelService.
  • Chỉ định nhãn cho chiến dịch bằng các yêu cầu CampaignLabelService.
  • Truy xuất và lọc kết quả báo cáo theo nhãn bằng GoogleAdsService các truy vấn.

Hướng dẫn này tập trung vào chiến dịch, nhưng bạn có thể sử dụng cùng một phương pháp cho nhóm quảng cáo, quảng cáo và từ khoá. API này cũng cung cấp CustomerLabelService, cho phép tài khoản người quản lý chỉ định nhãn cho tài khoản con.

Trường hợp sử dụng

Các trường hợp điển hình để sử dụng nhãn bao gồm như sau:

  • Tài khoản của bạn có các chiến dịch mà bạn chỉ bật vào một số thời điểm nhất định trong năm và bạn muốn đưa hoặc loại trừ các chiến dịch đó khỏi báo cáo.
  • Bạn đã thêm một nhóm từ khoá mới vào nhóm quảng cáo và muốn so sánh số liệu thống kê của nhóm từ khoá đó với các từ khoá khác trong nhóm quảng cáo.
  • Người dùng tài khoản Google Ads của bạn mỗi người quản lý một nhóm chiến dịch và bạn muốn có cách xác định nhóm chiến dịch cho từng người dùng.
  • Ứng dụng của bạn cần đánh dấu trạng thái của một số đối tượng.

Tạo nhãn

Tạo nhãn bằng đối tượng Label có trường text_label được đặt:

  1. Tạo một thực thể TextLabel chứa màu nền và nội dung mô tả.
  2. Tạo một thực thể Label và chỉ định TextLabel cho trường text_label của thực thể đó.
  3. Bọc Label trong LabelOperation (create) và gửi đến LabelService.MutateLabels.

Hãy ghi lại mã nhận dạng của nhãn đã tạo để sử dụng cho các truy vấn sau này. Mã nhận dạng được nhúng trong trường resource_name trong MutateLabelResult được trả về trong MutateLabelsResponse.

Bạn cũng có thể sử dụng yêu cầu GoogleAdsService Search hoặc SearchStream để truy xuất mã nhận dạng nhãn và tên tài nguyên.

Chỉ định nhãn

Bạn có thể chỉ định nhãn cho chiến dịch, khách hàng, nhóm quảng cáo, tiêu chí hoặc quảng cáo bằng cách sử dụng thao tác Mutate trong dịch vụ tương ứng.

Ví dụ: để chỉ định nhãn cho một chiến dịch, hãy chuyển một hoặc nhiều CampaignLabelOperation đối tượng đến CampaignLabelService.MutateCampaignLabels. Mỗi CampaignLabelOperation bao gồm một CampaignLabel thực thể, yêu cầu tên tài nguyên đầy đủ trong các trường sau:

  • label: Tên tài nguyên của một nhãn (ví dụ: customers/{customer_id}/labels/{label_id}).
  • campaign: Tên tài nguyên của một chiến dịch (ví dụ: customers/{customer_id}/campaigns/{campaign_id}).

Tạo một thực thể CampaignLabel cho từng cặp nhãn-chiến dịch. Bọc thực thể đó trong CampaignLabelOperation bằng thao tác create và gửi đến CampaignLabelService.MutateCampaignLabels.

Thêm nhãn chiến dịch

Sau đây là ví dụ về mã cho thấy cách thêm nhãn chiến dịch vào danh sách chiến dịch:

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

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

Chỉ định nhãn cho khách hàng

Việc chỉ định nhãn cho khách hàng là một nhiệm vụ thường gặp đối với tài khoản người quản lý để phân loại tài khoản khách hàng. Việc này được thực hiện bằng CustomerLabelService. Nhãn do tài khoản người quản lý tạo thuộc sở hữu của tài khoản người quản lý đó và chỉ xuất hiện khi được xác thực là tài khoản người quản lý sở hữu.

Mỗi CustomerLabelOperation bao gồm một CustomerLabel thực thể. Khi tạo mối quan hệ giữa khách hàng và nhãn, hãy lưu ý:

  • label: Trường này là bắt buộc và phải là tên tài nguyên của một nhãn do tài khoản người quản lý sở hữu, chẳng hạn như customers/{MANAGER_ID}/labels/{LABEL_ID}.
  • customer: Trường này chỉ dành cho đầu ra và không được đặt trong yêu cầu. Khách hàng được gắn nhãn được xác định bằng customer_id trong đường dẫn MutateCustomerLabelsRequest.

Truy xuất đối tượng bằng nhãn

Sau khi chỉ định nhãn cho chiến dịch, bạn có thể sử dụng các trường nhãn để truy xuất đối tượng theo mã nhận dạng.

Chuyển một truy vấn GAQL thích hợp đến GoogleAdsService Search hoặc SearchStream yêu cầu. Ví dụ: truy vấn sau đây trả về mã nhận dạng, tên và nhãn cho từng chiến dịch được liên kết với bất kỳ một trong ba mã nhận dạng nhãn:

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

Bạn chỉ có thể lọc theo mã nhận dạng nhãn, chứ không lọc theo tên nhãn. Để lấy mã nhận dạng nhãn từ tên nhãn, hãy sử dụng truy vấn sau:

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

Truy xuất nhãn được áp dụng cho khách hàng

Khi lấy hệ phân cấp tài khoản trong một tài khoản người quản lý, bạn có thể truy xuất danh sách nhãn được áp dụng cho tài khoản khách hàng con bằng cách yêu cầu trường applied_labels từ đối tượng CustomerClient. Trường này chỉ truy xuất các nhãn do khách hàng thực hiện lệnh gọi API sở hữu.

Sử dụng nhãn trong báo cáo

Sử dụng nhãn để cải thiện tính hữu ích của báo cáo.

Báo cáo nhãn

Tài nguyên báo cáo Nhãn trả về thông tin chi tiết về các nhãn được xác định trong một tài khoản. Thông tin chi tiết bao gồm tên, mã nhận dạng, tên tài nguyên, trạng thái, màu nền và nội dung mô tả, cũng như tài nguyên Khách hàng đại diện cho chủ sở hữu nhãn.

Báo cáo có chỉ số

Chế độ xem báo cáo Nhóm quảng cáo và Chiến dịch chứa trường labels. Dịch vụ báo cáo trả về tên tài nguyên nhãn ở định dạng customers/{customer_id}/labels/{label_id}. Ví dụ: tên tài nguyên customers/123456789/labels/012345 đề cập đến nhãn có mã nhận dạng 012345 trong tài khoản có mã nhận dạng 123456789.

Báo cáo không có chỉ số

Bạn có thể sử dụng từng tài nguyên báo cáo sau đây để tìm mối quan hệ giữa tài nguyên và nhãn:

Bạn có thể lọc các kết quả báo cáo này bằng cách so sánh trường label.id bằng bất kỳ toán tử so sánh số nào hoặc toán tử BETWEEN, IS NULL, IS NOT NULL, IN hoặc NOT IN.

Trong ví dụ này, bạn có thể nhận tất cả chiến dịch có một mã nhận dạng nhãn cụ thể:

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