Using temporary IDs

A powerful feature of BatchJobService is that it supports the use of temporary IDs.

You can do this by specifying the new resource's resource_name to use a negative ID. For example, if you create a campaign and specify its resource name as customers/<YOUR_CUSTOMER_ID>/campaigns/-1, then when you are creating the ad group in a later operation, you can reference it by that resource name and the -1 you specified will be replaced by the actual ID of the created campaign automatically.

Here are some things to keep in mind when using temporary resource names:

  • A temporary resource name can only be used after it's been defined in a resource. In the example below, the ad group operation would have to appear after the campaign operation in the list of operations.
  • Temporary resource names are not remembered across jobs or mutate requests; to reference a resource created in a previous job or mutate request, use its actual resource name.
  • For a single job or mutate request, each temporary resource name must use a unique negative number, even if they are from different resource types. If a temporary ID is reused in a single job or mutate request, then an error is returned.

Example

To give a more concrete example to the situation mentioned above, suppose you want to add a campaign, an ad group, and an ad in a single API request. You would create a structure for your request analogous to the following:

mutate_operations: [
  {
    campaign_operation: {
      create: {
        resource_name: "customers/<YOUR_CUSTOMER_ID>/campaigns/-1",
        ...
      }
    }
  },
  {
    ad_group_operation: {
      create: {
        resource_name: "customers/<YOUR_CUSTOMER_ID>/adGroups/-2",
        campaign: "customers/<YOUR_CUSTOMER_ID>/campaigns/-1"
        ...
      }
    }
  },
  {
    ad_group_ad_operation: {
      create: {
        ad_group: "customers/<YOUR_CUSTOMER_ID>/adGroups/-2"
        ...
      }
    }
  },
]

Notice that a new temporary ID is used for the ad group, since we can't reuse the -1 that we used for the campaign, and we also reference this ad group when creating an ad group ad. The ad group itself references the resource name we established for the campaign in an earlier operation in the request, while resource_name in ad_group_ad_operation is not necessary since no further operation is referencing it.