概要

構造化データファイル(SDF)は、ディスプレイ&ビデオ 360 のリソースに関するデータを一括で取得および更新するために使用される、特別な形式のカンマ区切り値(CSV)ファイルです。ディスプレイ&ビデオ 360 API を使用すると、カスタマイズした SDF を生成してダウンロードできます。これにより、ディスプレイ&ビデオ 360 リソースの整理されたフィルタリング済みのデータを取得できます。

このガイドでは、SDF ダウンロード オペレーションを作成し、そのオペレーションを追跡して、結果の SDF をダウンロードする方法について説明します。

SDF の形式とバージョニングについては、SDF リファレンス ドキュメントをご覧ください。

タスクを作成する

SDF は、sdfdownloadtask と呼ばれる非同期オペレーションによって生成されます。このタスクを作成するときに、必要な SDF に関するパラメータを定義します。この処理は、sdfdownloadtasks.create メソッドを介して行われます。以降のサブセクションでは、設定可能なパラメータについて説明します。

バージョンを指定する

構造化データファイルの形式は、ディスプレイ&ビデオ 360 API とは別に定期的に更新され、新バージョンがリリースされ、以前のバージョンは定期的に非推奨になります。このため、常に最新バージョンの SDF を使用することをおすすめします

目的の SDF の SDF バージョンは、リクエスト本文の version フィールドを使用して設定します。設定されていない場合、または SDF_VERSION_UNSPECIFIED に設定されている場合、タスクは SDF コンテンツのコンテキストとして使用される広告主またはパートナー リソースのデフォルトの SDF バージョンを使用します。

コンテキストを設定する

利用可能なリソースのデータを含む SDF を生成できますが、個々の SDF は 1 つのパートナーまたは広告主のコンテキスト内のコンテンツのみを返します。このコンテキストは、リクエストの本文で partnerId フィールドまたは advertiserId フィールドのいずれかによって定義されます。これらの 2 つのフィールドのいずれかを設定する必要があります。

指定されたコンテキスト内のリソースのみが、結果の SDF に含まれます。指定したパートナーまたは広告主が所有していないリソースでフィルタしようとすると、そのリソースもそのリソースのコンテンツも結果に含まれません。これらの含まれていないリソースのみでフィルタリングすると、結果のファイルは空になります。指定されたコンテキスト外のリソースでフィルタしようとしても、エラーは返されません。コンテキストが正しいことを確認してください。

適切なフィルタを選択する

上記のコンテキストに加えて、生成するファイルタイプと、含める特定のリソースまたはリソース ファミリーを指定することで、生成される構造化データファイルのスコープをさらにフィルタできます。

sdfdownloadtask には 3 つのフィルタがあり、それぞれ特定の仕様タイプに対応しています。1 つの sdfdownloadtask に割り当てられるのは 1 つだけです。

ParentEntityFilter

ParentEntityFilter は、使用可能なフィルタの中で最も広範囲です。

fileType フィールドを使用すると、タスクで生成するすべての必要なファイル形式を一覧表示できます。これは必須です。空のままにするか、FILE_TYPE_UNSPECIFIED に設定すると、sdfdownloadtask はエラーで完了します。

filterType フィールドと filterIds フィールドを使用すると、結果をさらに絞り込むことができます。filterType は、フィルタするリソースのタイプを指定します。filterIds は、一意の ID でリソースを識別します。結果の SDF には、filterTypefilterIds で識別されるリソースまたはその子リソースである fileType で識別されるリソースが含まれます。

IdFilter

IdFilter は、リクエストをフィルタして、識別されたリソースのみを含めます。

IdFilter には、在庫ソースを除くすべての SDF タイプに対応するフィールドがあります。これらの各フィールドは、生成する SDF に含める特定のリソースを識別する一意の ID のリストです。指定する ID はコンテキスト セット内に存在する必要がありますが、直接関連している必要はありません。広告申込情報を含むキャンペーンをリクエストするために、特定のキャンペーンをリクエストする必要はありません。その逆も同様です。生成されるファイルタイプは、IdFilter で特定されたリソースに対応するもののみです。

InventorySourceFilter

InventorySourceFilter では、広告枠ソース リソースを含む SDF のフィルタリングとダウンロードのみが可能です。これは、Inventory Source リソースに関する情報を取得するために使用できる唯一のフィルタです。

InventorySourceFilter には、SDF に含めるインベントリ ソース リソースの一意の ID を指定する単一の inventorySourceIds フィールドがあります。inventorySourceIds に指定されたリストが空の場合、設定されたコンテキストのすべての広告枠ソースが生成された SDF に含まれます。

リクエストを作成する

目的の SDF のパラメータがわかったら、リクエストを作成して sdfdownloadtask を作成できます。

次に、ParentEntityFilter を使用して sdfdownloadtask を作成する方法の例を示します。

Java

// Create the filter structure
ParentEntityFilter parentEntityFilter = new ParentEntityFilter();
parentEntityFilter.setFileType(sdf-file-type-list);
parentEntityFilter.setFilterType(sdfFilterType);
parentEntityFilter.setFilterIds(filter-id-list);

// Configure the sdfdownloadtasks.create request
Sdfdownloadtasks.Create request =
   service
       .sdfdownloadtasks()
       .create(
           new CreateSdfDownloadTaskRequest()
               .setVersion(sdfVersion)
               .setAdvertiserId(advertiserId)
               .setParentEntityFilter(parentEntityFilter)
       );

// Create the sdfdownloadtask
Operation operationResponse = request.execute();

System.out.printf("Operation %s was created.\n",
   operationResponse.getName());

Python

# Configure the sdfdownloadtasks.create request
createSdfDownloadTaskRequest = {
    'version': sdf-version,
    'advertiserId': advertiser-id,
    'parentEntityFilter': {
        'fileType': sdf-file-type-list,
        'filterType': sdf-filter-type,
        'filterIds': filter-id-list
    }
}

# Create the sdfdownloadtask
operation = service.sdfdownloadtasks().create(
    body=createSdfDownloadTaskRequest).execute();

print("Operation %s was created." % operation["name"])

PHP

// Create the sdfdownloadtasks.create request structure
$createSdfDownloadTaskRequest =
    new Google_Service_DisplayVideo_CreateSdfDownloadTaskRequest();
$createSdfDownloadTaskRequest->setAdvertiserId(advertiser-id);
$createSdfDownloadTaskRequest->setVersion(sdf-version);

// Create and set the parent entity filter
$parentEntityFilter = new Google_Service_DisplayVideo_ParentEntityFilter();
$parentEntityFilter->setFileType(sdf-file-type-list);
$parentEntityFilter->setFilterType(sdf-filter-type);
if (!empty(filter-id-list)) {
    $parentEntityFilter->setFilterIds(filter-id-list);
}
$createSdfDownloadTaskRequest->setParentEntityFilter($parentEntityFilter);

// Call the API, creating the SDF Download Task.
$operation = $this->service->sdfdownloadtasks->create(
    $createSdfDownloadTaskRequest
);

printf('Operation %s was created.\n', $operation->getName());

リクエストを確認してダウンロード パスを取得する

sdfdownloadtask を作成すると、オペレーション オブジェクトが返されます。このオペレーションは、作成時の非同期 SDF 生成オペレーションのステータスを表します。sdfdownloadtasks.operations.get メソッドを使用すると、オペレーションが完了してダウンロードの準備が整ったか、エラーが発生したかを確認できます。

終了すると、返されるオペレーションの done フィールドが null 以外になります。完了したオペレーションには、response フィールドまたは error フィールドのいずれかが含まれます。error フィールドが存在する場合、Status オブジェクトには、発生したエラーの詳細を示すエラーコードメッセージが含まれます。response フィールドが存在する場合、ダウンロード用に生成されたファイルを識別する resourceName 値を持つオブジェクトが含まれます。

指数バックオフを使用してリクエストを確認する方法の例を次に示します。

Java

String operationName = operationResponse.getName();

// Configure the Operations.get request
Sdfdownloadtasks.Operations.Get operationRequest =
   service
       .sdfdownloadtasks()
       .operations()
       .get(operationName);

// Configure exponential backoff for checking the status of our operation
ExponentialBackOff backOff = new ExponentialBackOff.Builder()
   .setInitialIntervalMillis(5000) // setting initial interval to five seconds
   .setMaxIntervalMillis(300000)  // setting max interval to five minutes
   .setMaxElapsedTimeMillis(18000000) // setting max elapsed time to five hours
   .build();

while (operationResponse.getDone() == null) {
 long backoffMillis = backOff.nextBackOffMillis();
 if (backoffMillis == ExponentialBackOff.STOP) {
   System.out.printf("The operation has taken more than five hours to
       complete.\n");
   return;
 }
 Thread.sleep(backoffMillis);

 // Get current status of operation
 operationResponse = operationRequest.execute();
}

// Check if the operation finished with an error and return
if (operationResponse.getError() != null) {
 System.out.printf("The operation finished in error with code %s: %s\n",
     operationResponse.getError().getCode(), operationResponse.getError()
         .getMessage());
 return;
}

System.out.printf(
    "The operation completed successfully. Resource %s was created.\n",
    operationResponse.getResponse().get("resourceName").toString());

Python

# The following values control retry behavior while
# the report is processing.
# Minimum amount of time between polling requests. Defaults to 5 seconds.
min_retry_interval = 5
# Maximum amount of time between polling requests. Defaults to 5 minutes.
max_retry_interval = 5 * 60
# Maximum amount of time to spend polling. Defaults to 5 hours.
max_retry_elapsed_time = 5 * 60 * 60

# Configure the Operations.get request
get_request = service.sdfdownloadtasks().operations().get(
  name=operation["name"]
)

sleep = 0
start_time = time.time()
while True:
  # Get current status of operation
  operation = get_request.execute()

  if "done" in operation:
    if "error" in operation:
      print("The operation finished in error with code %s: %s" % (
            operation["error"]["code"],
            operation["error"]["message"]))
    else:
      print("The operation completed successfully. Resource %s was created."
            % operation["response"]["resourceName"])
    break
  elif time.time() - start_time > max_retry_elapsed_time:
    print("Generation deadline exceeded.")

  sleep = next_sleep_interval(sleep)
  print("Operation still running, sleeping for %d seconds." % sleep)
  time.sleep(sleep)

def next_sleep_interval(previous_sleep_interval):
  """Calculates the next sleep interval based on the previous."""
  min_interval = previous_sleep_interval or min_retry_interval
  max_interval = previous_sleep_interval * 3 or min_retry_interval
  return min(max_retry_interval, random.randint(min_interval, max_interval))

PHP

// The following values control retry behavior
// while the task is processing.
// Minimum amount of time between polling requests. Defaults to 5 seconds.
$minRetryInterval = 5;
// Maximum amount of time between polling requests. Defaults to 5 minutes.
$maxRetryInterval = 300;
// Maximum amount of time to spend polling. Defaults to 5 hours.
$maxRetryElapsedTime = 18000;

$operationName = $operation->getName();

$sleepInterval = 0;
$startTime = time();

while (!$operation->getDone()) {
    if ($sleepInterval != 0) {
        printf(
            'The operation is still running, sleeping for %d seconds\n',
            $sleepInterval
        );
    }

    // Sleep before retrieving the SDF Download Task again.
    sleep($sleepInterval);

    // Call the API, retrieving the SDF Download Task.
    $operation = $this->service->sdfdownloadtasks_operations->get(
        $operation->getName()
    );

    // If the operation has exceeded the set deadline, throw an exception.
    if (time() - $startTime > $maxRetryElapsedTime) {
        printf('SDF download task processing deadline exceeded\n');
        throw new Exception(
            'Long-running operation processing deadline exceeded'
        );
    }

    // Generate the next sleep interval using exponential backoff logic.
    $sleepInterval = min(
        $maxRetryInterval,
        rand(
            max($minRetryInterval, $previousSleepInterval),
            max($minRetryInterval, $previousSleepInterval * 3)
        )
    );
}

// If the operation finished with an error, throw an exception.
if($operation->getError() !== null) {
    $error = $operation->getError();
    printf(
        'The operation finished in error with code %s: %s\n',
        $error->getCode(),
        $error->getMessage()
    );
    throw new Exception($error->getMessage());
}

// Print successfully generated resource.
$response = $operation->getResponse();
printf(
    'The operation completed successfully. Resource %s was '
        . 'created. Ready to download.\n',
    $response['resourceName']
);