概要

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

このガイドでは、SDF のダウンロード オペレーションの作成方法、そのオペレーションのトラッキング方法、作成された SDF ファイルのダウンロード方法について説明します。

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

タスクを作成する

SDF は、sdfdownloadtask と呼ばれる非同期処理によって生成されます。このタスクを作成する際に、目的の SDF ファイルに関するパラメータを定義します。 そのためには、sdfdownloadtasks.create メソッドを使用します。以降のサブセクションでは、設定できるパラメータについて説明します。

バージョンを指定する

構造化データファイル形式は、Display & Video 360 API とは関係なく定期的に更新され、新しいバージョンがリリースされ、古いバージョンは定期的にサポート終了となります。そのため、常に最新バージョンの SDF を使用することをおすすめします

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

コンテキストを決める

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

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

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

前述のコンテキスト セットに加えて、生成するファイル形式と、含める特定のリソースまたはリソース ファミリーを指定することで、生成される構造化データファイルの範囲をさらにフィルタリングできます。

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

ParentEntityFilter

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

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

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

IdFilter

IdFilter は、識別されたリソースのみが含まれるようにリクエストをフィルタします。

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

InventorySourceFilter

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

InventorySourceFilter には単一の inventorySourceIds フィールドがあります。このフィールドは、SDF ファイルに含めるインベントリ ソース リソースの一意の ID を指定します。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 メソッドを使用して、オペレーションが完了してダウンロードの準備ができているか、あるいはエラーがスローされたかを確認できます。

終了すると、返されるオペレーションには null でない done フィールドが含まれます。終了したオペレーションには、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']
);