ビルダーとは
ビルダーを使用してエンティティを追加します。
Campaign などの各親オブジェクトには、子エンティティの追加に使用するビルダー オブジェクトを取得するためのメソッドが含まれています。 たとえば、キャンペーンに広告グループを追加するには、オブジェクトのnewAdGroupBuilder
メソッドをCampaign
呼び出します。
ビルダー オブジェクトには、エンティティのプロパティ値を設定するために使用するメソッドが含まれています。 たとえば、キーワードの CPC を指定するには、 メソッドを使用します withCpc
。 エンティティのすべてのプロパティ値を設定したら、 メソッドを build
呼び出してエンティティを作成します。 ビルド プロセスは非同期プロセスであり、要求は他のビルド要求と共にキューに入れ、バッチで処理されます。 バッチ処理された要求は、スクリプトが終了する前に完了します。
ビルド要求が成功したかどうかを判断するには、ログを確認するか、メソッドから返される操作オブジェクトを build
使用できます。 たとえば、 AdGroupBuilder はAdGroupOperation を返します。 操作オブジェクトの任意のメソッド (isSuccessful
、、またはgetErrors
) を呼び出して、getResult
スクリプトによってエンティティが正常に作成されたかどうかを判断できます。 ただし、これらのメソッドを呼び出すときのパフォーマンスに関する考慮事項があります ( 「パフォーマンスに関する考慮事項」を参照してください)。
次の例では、ビルダー オブジェクトと操作オブジェクトを使用してキーワードを作成する方法を概念的に示します。 このフローは、単一のエンティティ (または少数) を作成している場合にのみ使用する必要があります。
// Gets the first ad group in the account.
var adGroup = AdsApp.adGroups().get().next();
// Use the 'with' methods to specify the keyword's property values.
// The .build() method adds the build request to the build queue.
var keywordOperation = adGroup.newKeywordBuilder()
.withCpc(1.2)
.withText("shirts")
.withFinalUrl("https://www.contoso.com/shirts")
.build();
// Call isSuccessful() to determine if the build succeeded.
// Calling any of the operation object's method processes the
// build request immediately.
if (keywordOperation.isSuccessful()) {
// You only need to call getResult if you need to access
// the new keyword entity.
var keyword = keywordOperation.getResult();
} else {
// Handle the errors.
for (var error of keywordOperation.getErrors()) {
Logger.log(`${error}\n`);
}
}
パフォーマンスに関する考慮事項
パフォーマンスを向上させるために、スクリプトはビルド要求をバッチ処理します。 ビルド要求の操作メソッドを呼び出すと、スクリプトはキューに登録されたビルド要求を直ちに処理し、パフォーマンスの向上を否定します。 複数のエンティティを作成する場合は、エンティティのビルドに使用するのと同じループで操作メソッドを実行しないでください。 一度に処理されるエンティティは 1 つだけであるため、パフォーマンスが低下します。 代わりに、操作の配列を作成し、ビルド ループの後に処理します。
操作
// An array to hold the operations, so you
// can process them after all the entities are queued.
var operations = [];
// Create all the new entities.
for (var i = 0; i < keywords.length; i++) {
var keywordOperation = AdsApp.adGroups().get().next()
.newKeywordBuilder()
.withText(keywords[i])
.build();
operations.push(keywordOperation);
}
// Now call the operation method so the build requests
// get processed in batches.
for (var i = 0; i < operations.length; i++) {
var newKeyword = operations[i].getResult();
}
こうしないでください
for (var i = 0; i < keywords.length; i++) {
var keywordOperation = AdsApp.adGroups().get().next()
.newKeywordBuilder()
.withText(keywords[i])
.build();
// Don't get results in the same loop that creates
// the entity because Scripts then only processes one
// entity at a time.
var newKeyword = keywordOperation.getResult();
}
ビルダーの一覧を次に示します。