Google Ads API에서는 필드 마스크를 사용하여 업데이트가 이루어집니다. 필드 마스크 (google.protobuf.FieldMask)에는 업데이트를 통해 변경하려는 snake_case의 필드 경로 목록이 포함되어 있습니다. 필드 마스크에 없는 지정된 필드는 서버로 전송되더라도 무시됩니다.
FieldMasks 유틸리티
Java 클라이언트 라이브러리에서 필드 마스크를 생성하는 권장 방법은 수정된 객체에서 필드 마스크를 생성하여 처음부터 빌드하는 대신 내장된 FieldMasks 유틸리티 클래스를 사용하는 것입니다.
다음은 캠페인을 업데이트하는 예입니다.
// Creates a Campaign object with the proper resource name and any other
// changes.
Campaign campaign =
Campaign.newBuilder()
.setResourceName(ResourceNames.campaign(customerId, campaignId))
.setStatus(CampaignStatus.PAUSED)
.build();
// Constructs an operation that updates the campaign, using the
// FieldMasks.allSetFieldsOf utility to derive the update mask. This mask tells
// the Google Ads API which attributes of the campaign you want to change.
CampaignOperation operation =
CampaignOperation.newBuilder()
.setUpdate(campaign)
.setUpdateMask(FieldMasks.allSetFieldsOf(campaign))
.build();
// Sends the operation in a mutate request.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
customerId.toString(), Collections.singletonList(operation));
이 예시에서는 먼저 빈 Campaign 빌더를 만들고 API가 업데이트되는 캠페인을 알 수 있도록 리소스 이름을 설정합니다.
그런 다음 이 예에서는 캠페인에서 FieldMasks.allSetFieldsOf()를 호출하여 설정된 모든 필드를 열거하는 필드 마스크를 자동으로 생성합니다. 반환된 마스크를 업데이트 호출에 직접 전달할 수 있습니다.
기존 객체를 사용하고 일부 필드를 업데이트해야 하는 경우 다음과 같이 FieldMasks.compare()를 사용합니다.
// Assumes existingCampaign was retrieved from a previous API call.
// Creates a new campaign based on the existing campaign and updates the
// campaign by setting its status to paused.
Campaign campaignToUpdate =
existingCampaign.toBuilder()
.setStatus(CampaignStatus.PAUSED)
.build();
// Constructs an operation that updates the campaign, using the
// FieldMasks.compare utility to derive the update mask. This mask tells the
// Google Ads API which attributes of the campaign you want to change.
CampaignOperation operation =
CampaignOperation.newBuilder()
.setUpdate(campaignToUpdate)
.setUpdateMask(FieldMasks.compare(existingCampaign, campaignToUpdate))
.build();
// Sends the operation in a mutate request.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
customerId.toString(), Collections.singletonList(operation));
처음부터 필드 마스크를 만들려면 FieldMask 빌더를 만들고 변경하려는 각 필드의 snake_case 이름을 추가합니다.
FieldMask fieldMask =
FieldMask.newBuilder()
.addPaths("status")
.addPaths("name")
.build();
메시지 필드 및 하위 필드 업데이트
MESSAGE 필드에는 하위 필드 (예: target_cpa_micros, cpc_bid_ceiling_micros, cpc_bid_floor_micros이 있는 MaximizeConversions)가 있을 수도 있고 하위 필드가 없을 수도 있습니다 (예: ManualCpm).
정의된 하위 필드가 없는 메시지 필드
하위 필드가 정의되지 않은 MESSAGE 필드를 업데이트할 때는 앞 섹션에 설명된 대로 FieldMasks 유틸리티를 사용하여 필드 마스크를 생성하세요.
하위 필드가 정의된 메시지 필드
메시지에서 하위 필드를 명시적으로 설정하지 않고 하위 필드가 정의된 MESSAGE 필드를 업데이트할 때는 처음부터 필드 마스크를 만드는 것과 마찬가지로 FieldMask에 변경 가능한 MESSAGE 하위 필드를 각각 수동으로 추가해야 합니다.
일반적인 예로 새 입찰 전략의 필드를 설정하지 않고 캠페인의 입찰 전략 (oneof 필드 campaign_bidding_strategy)을 업데이트하는 경우가 있습니다. 다음 예에서는 입찰 전략의 하위 필드를 설정하지 않고 MaximizeConversions 입찰 전략을 사용하도록 캠페인을 업데이트하는 방법을 보여줍니다.
이 경우 FieldMasks의 allSetFieldsOf() 및 compare() 메서드만으로는 의도한 목표를 달성할 수 없습니다.
다음 예시에서는 maximize_conversions가 포함된 필드 마스크를 생성합니다. 하지만 Google Ads API는 업데이트 마스크에 하위 필드가 있는 최상위 메시지 경로를 허용하지 않으며 (하위 필드가 실수로 삭제되는 것을 방지하기 위해) FieldMaskError.FIELD_HAS_SUBFIELDS 오류를 반환합니다.
// Creates a campaign with the proper resource name and an empty
// MaximizeConversions field.
Campaign campaign =
Campaign.newBuilder()
.setResourceName(ResourceNames.campaign(customerId, campaignId))
.setMaximizeConversions(MaximizeConversions.newBuilder().build())
.build();
// Constructs an operation using FieldMasks.allSetFieldsOf to derive the update
// mask. The field mask includes 'maximize_conversions', which produces a
// FieldMaskError.FIELD_HAS_SUBFIELDS error.
CampaignOperation operation =
CampaignOperation.newBuilder()
.setUpdate(campaign)
.setUpdateMask(FieldMasks.allSetFieldsOf(campaign))
.build();
// Sends the operation in a mutate request that results in a
// FieldMaskError.FIELD_HAS_SUBFIELDS error because empty MESSAGE fields with
// subfields cannot be included directly in a field mask.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
customerId.toString(), Collections.singletonList(operation));
다음 예에서는 하위 필드를 설정하지 않고 MaximizeConversions 입찰 전략을 사용하도록 캠페인을 올바르게 업데이트하는 방법을 보여줍니다.
표준 및 포트폴리오 입찰 전략 할당에 대해 자세히 알아보세요.
// Creates a Campaign object with the proper resource name.
Campaign campaign =
Campaign.newBuilder()
.setResourceName(ResourceNames.campaign(customerId, campaignId))
.build();
// Creates a field mask from the campaign and adds the mutable subfield
// ('maximize_conversions.target_cpa_micros') on the MaximizeConversions
// bidding strategy to the field mask. Because this subfield is included in the
// field mask while excluded from the campaign object, the Google Ads API
// switches the campaign's bidding strategy oneof to MaximizeConversions with
// target_cpa_micros unset.
FieldMask fieldMask =
FieldMasks.allSetFieldsOf(campaign).toBuilder()
.addPaths("maximize_conversions.target_cpa_micros")
.build();
// Creates an operation to update the campaign with the specified fields.
CampaignOperation operation =
CampaignOperation.newBuilder()
.setUpdate(campaign)
.setUpdateMask(fieldMask)
.build();
필드 지우기
일부 필드는 명시적으로 지울 수 있습니다. 앞의 예와 마찬가지로 메시지 객체에서 설정되지 않은 상태로 유지하면서 필드 마스크에 이러한 필드를 명시적으로 추가해야 합니다. 예를 들어 MaximizeConversions 입찰 전략을 사용하는 캠페인이 있고 target_cpa_micros 필드가 0보다 큰 값으로 설정되어 있다고 가정해 보겠습니다.
다음 코드는 실행되지만 maximize_conversions.target_cpa_micros가 의도한 대로 지워지지 않습니다.
// Creates a campaign with the proper resource name and a MaximizeConversions
// object with target_cpa_micros set to 0L.
Campaign campaign =
Campaign.newBuilder()
.setResourceName(ResourceNames.campaign(customerId, campaignId))
.setMaximizeConversions(
MaximizeConversions.newBuilder().setTargetCpaMicros(0L).build())
.setStatus(CampaignStatus.PAUSED)
.build();
// Constructs an operation using FieldMasks.allSetFieldsOf to derive the
// update mask.
CampaignOperation operation =
CampaignOperation.newBuilder()
.setUpdate(campaign)
.setUpdateMask(FieldMasks.allSetFieldsOf(campaign))
.build();
// Sends the operation in a mutate request that does not clear the field
// cleanly.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
customerId.toString(), Collections.singletonList(operation));
다음 예에서는 MaximizeConversions 입찰 전략에서 target_cpa_micros 필드를 올바르게 지우는 방법을 보여줍니다.
// Creates a Campaign object with the proper resource name.
Campaign campaign =
Campaign.newBuilder()
.setResourceName(ResourceNames.campaign(customerId, campaignId))
.build();
// Constructs a field mask from the campaign and adds the
// 'maximize_conversions.target_cpa_micros' field to the field mask, which
// clears this field from the bidding strategy without impacting any other
// fields on the bidding strategy.
FieldMask fieldMask =
FieldMasks.allSetFieldsOf(campaign).toBuilder()
.addPaths("maximize_conversions.target_cpa_micros")
.build();
// Creates an operation to update the campaign with the specified field.
CampaignOperation operation =
CampaignOperation.newBuilder()
.setUpdate(campaign)
.setUpdateMask(fieldMask)
.build();