什么是生成器?

使用生成器添加实体。 每个父对象(如 Campaign)都包含用于获取用于添加子实体的生成器对象的方法。 例如,若要向市场活动添加广告组,需要调用 对象的 CampaignnewAdGroupBuilder 方法。

builder 对象包括用于设置实体属性值的方法。 例如,若要指定关键字 (keyword) 的 CPC,请使用 withCpc 方法。 设置实体的所有属性值后,将调用 build 方法来创建实体。 生成过程是一个异步过程,其中请求与其他生成请求一起排队,并在批处理中进行处理。 批处理的请求将在脚本终止之前完成。

若要确定生成请求是否成功,可以查看日志,也可以使用方法返回的操作对象 build 。 例如, AdGroupBuilder 返回 AdGroupOperation。 可以调用操作对象的任意方法 (isSuccessfulgetResultgetErrors) ,以确定脚本是否成功创建了实体。 但是,调用这些方法时存在性能注意事项 (请参阅 性能注意事项) 。

以下示例在概念上演示如何使用生成器和操作对象创建关键字 (keyword) 。 仅当创建单个实体 (或几个) 时,才应使用此流。

    // 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`);
        }
    }

性能注意事项

为了提高性能,脚本会批量处理生成请求。 如果调用生成请求的操作方法,它将强制脚本立即处理排队的生成请求,以消除任何性能提升。 如果要创建多个实体,请不要在用于生成实体的同一循环中执行操作方法。 这会导致性能不佳,因为一次只处理一个实体。 相反,创建操作数组并在生成循环后进行处理。

具体操作

    // 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();
    }

下面是生成器列表。

后续步骤