このセクションでは、時間的制約のあるインベントリ エンティティの更新を Google に送信する方法について説明します。Incremental Update API を使用すると、サンドボックスまたは本番環境のインベントリの更新をプッシュし、ほぼリアルタイムでエンティティを削除できます。
この機能は主に、緊急閉鎖など、予測できない更新を目的としています。原則として、Incremental Update API で送信する変更は、1 時間以内に公開される変更である必要があります。変更をすぐに反映する必要がない場合は、代わりにバッチ取り込みを使用できます。増分アップデートは 5 分以内に処理されます。
前提条件
増分アップデートを実装する前に、以下の作業が必要です。
- Actions プロジェクトの編集者ロールを持つサービス アカウントが作成されます。詳しくは、プロジェクトを作成して設定するをご覧ください。
- 本番環境またはサンドボックスのデータフィードがホストされ、取り込まれます。詳細については、バッチ取り込みをご覧ください。
- (省略可、ただし推奨)API の呼び出し時に OAuth 2.0 を簡単に使用できるように、任意の言語で Google クライアント ライブラリをインストールします。以下のコードサンプルでは、これらのライブラリが使用されています。それ以外の場合は、OAuth 2.0 を使用した Google API へのアクセスの説明に従ってトークン交換を手動で処理する必要があります。
エンドポイント
以下のリクエストで、次のように置き換えます。
- PROJECT_ID: プロジェクトの作成と設定で作成したプロジェクトに関連付けられた Google Cloud プロジェクト ID。
- TYPE: 更新するデータフィード内のオブジェクトのエンティティ タイプ(
@type
プロパティ)。 - ENTITY_ID(削除エンドポイントのみ): 削除するエンティティの ID。エンティティ ID は URL エンコードしてください。
- DELETE_TIME(削除エンドポイントのみ): システムでエンティティが削除された時刻を示すオプション フィールド(デフォルトはリクエストを受信したとき)。時刻に将来の時刻は指定できません。増分呼び出しでエンティティを送信する場合、エンティティのバージョニングは、削除呼び出しの際に
delete_time
フィールドも使用します。この値をyyyy-mm-ddTHH:mm:ssZ
の形式で指定します。
エンドポイントの更新
エンティティを変更するには、次のエンドポイントに HTTP POST リクエストを行い、更新と追加のペイロードを含めます。1 回の API 呼び出しで最大 1,000 個のエンティティを更新できます。
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities:batchPush
たとえば、ID が「delivery-provider-id」であるプロジェクトのエンティティを更新する場合、エンドポイントは次のようになります。
https://actions.googleapis.com/v2/apps/delivery-provider-id/entities:batchpush
エンドポイントの削除
インベントリのエンティティを削除するには、次のエンドポイントに HTTP DELETE リクエストを行います。
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/TYPE/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
たとえば、「delivery-provider-id」プロジェクトから ID「menuSection_122」の「MenuSection」エンティティを削除するには、次のように HTTP DELETE API 呼び出しを行います。
https://actions.googleapis.com/v2/apps/delivery-provider-id/entities/MenuSection/menuSection_122?entity.vertical=FOODORDERING
サンドボックス環境
サンドボックス インベントリで Incremental Update API を使用するには、上記のエンドポイントのガイダンスに従ってください。ただし、/v2/apps/
ではなく /v2/sandbox/apps/
にリクエストを送信します。
https://actions.googleapis.com/v2/sandbox/apps/PROJECT_ID/entities:batchPush
https://actions.googleapis.com/v2/sandbox/apps/PROJECT_ID/entities/TYPE/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
エンティティの更新
各 POST リクエストには、リクエスト パラメータと、インベントリ スキーマにリストされている任意のエンティティ タイプの構造化データを含む JSON ペイロードを含める必要があります。
ペイロードを更新する
JSON はバッチフィードの場合と同じように表示されますが、次の点が異なります。
- ペイロードの本文のサイズは 5 MB を超えないようにしてください。バッチフィードと同様に、より多くのデータを適合させるために空白を削除することをおすすめします。
- エンベロープは次のとおりです。
{ "requests": [ { "entity": { "data":"ENTITY_DATA", "name": "apps/project_id>/entities/type/entity_id" }, "update_time":"UPDATE_TIMESTAMP" }, ], "vertical": "FOODORDERING" }
上記のペイロードで、次のように置き換えます。
- ENTITY_DATA: 文字列としてシリアル化された JSON 形式のエンティティ。JSON-LD エンティティは、
data
フィールドに文字列として渡す必要があります。 - UPDATE_TIMESTAMP(省略可): システムでエンティティが更新された時点のタイムスタンプ。時刻に将来の時刻は指定できません。デフォルトのタイムスタンプは、Google がリクエストを受け取った時点です。増分リクエストでエンティティを送信する場合、追加/更新リクエストの場合、エンティティのバージョニングも
update_time
フィールドを使用します。
例
例 1: レストランの更新
レストランの電話番号を緊急に更新する必要があるとします。アップデートには、レストラン全体の JSON が含まれています。
次のようなバッチフィードについて考えてみましょう。
{ "@type": "Restaurant", "@id": "restaurant12345", "name": "Some Restaurant", "url": "https://www.provider.com/somerestaurant", "telephone": "+16501234567", "streetAddress": "345 Spear St", "addressLocality": "San Francisco", "addressRegion": "CA", "postalCode": "94105", "addressCountry": "US", "latitude": 37.472842, "longitude": -122.217144 }
この場合、HTTP POST による増分アップデートは次のようになります。
POST v2/sandbox/apps/provider-project/entities:batchPush Host: actions.googleapis.com Content-Type: application/ld+json { "requests": [ { "entity": { "name": "apps/provider-project/entities/restaurant/restaurant12345", "data": { "@type": "Restaurant", "@id": "restaurant12345", "name": "Some Restaurant", "url": "https://www.provider.com/somerestaurant", "telephone": "+16501235555", "streetAddress": "345 Spear St", "addressLocality": "San Francisco", "addressRegion": "CA", "postalCode": "94105", "addressCountry": "US", "latitude": 37.472842, "longitude": -122.217144 } } } "vertical": "FOODORDERING" }
例 2: 複数のレストランを更新する
1 回の API 呼び出しで 2 つのレストラン エンティティを更新するには、HTTP POST リクエストは次のようになります。
POST v2/sandbox/apps/provider-project/entities:batchPush Host: actions.googleapis.com Content-Type: application/ld+json { "requests": [ { "entity": { "name": "apps/provider-project/entities/restaurant/restaurant12345", "data": { "@type": "Restaurant", "@id": "restaurant12345", "name": "Some Restaurant", "url": "https://www.provider.com/somerestaurant", "telephone": "+16501235555", "streetAddress": "345 Spear St", "addressLocality": "San Francisco", "addressRegion": "CA", "postalCode": "94105", "addressCountry": "US", "latitude": 37.472842, "longitude": -122.217144 } } }, { "entity": { "name": "apps/provider-project/entities/restaurant/restaurant123", "data": { "@type": "Restaurant", "@id": "restaurant123", "name": "Some Other Restaurant", "url": "https://www.provider.com/somerestaurant", "telephone": "+16501231235", "streetAddress": "385 Spear St", "addressLocality": "San Mateo", "addressRegion": "CA", "postalCode": "94115", "addressCountry": "US" } } } ] "vertical": "FOODORDERING" }
例 3: メニュー アイテムの価格を更新する
メニュー アイテムの価格を変更する必要があるとします。例 1 と同様に、更新には最上位エンティティ(メニュー)全体の JSON が含まれている必要があります。フィードでは v1 在庫スキーマを使用します。
次のようなバッチフィードについて考えてみましょう。
{ "@type": "MenuItemOffer", "@id": "menuitemoffer6680262", "sku": "offer-cola", "menuItemId": "menuitem896532", "price": 3.00, "priceCurrency": "USD" }
この場合、POST による増分アップデートは次のようになります。
POST v2/sandbox/apps/provider-project/entities:batchPush Host: actions.googleapis.com Content-Type: application/ld+json { "requests": [ { "entity": { "name": "apps/provider-project/entities/menuitemoffer/menuitemoffer6680262", "data": { "@type": "MenuItemOffer", "@id": "menuitemoffer6680262", "sku": "offer-cola", "menuItemId": "menuitem896532", "price": 1.00, "priceCurrency": "USD" }, "vertical": "FOODORDERING" } } ] "vertical": "FOODORDERING" }
エンティティの追加
エンティティを追加するには、在庫の更新を使用しないでください。代わりに、v2 在庫スキーマの説明に沿ってバッチフィードのプロセスを使用してください。
エンティティの削除
最上位エンティティを削除するには、少し変更したエンドポイントを使用し、リクエストで HTTP POST ではなく HTTP DELETE を使用します。
最上位エンティティの削除
フィード内のレストランを削除したい状況について考えてみましょう。サービスとメニューも削除する必要があります。
ID が「provider/restaurant/menu/nr」のメニュー エンティティのサンプル エンドポイント:
DELETE v2/apps/delivery-provider-id/entities/menu/provider%2Frestaurant%2Fmenu%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
ID が「https://www.provider.com/restaurant/nr」であるレストラン エンティティのサンプル エンドポイント:
DELETE v2/apps/delivery-provider-id/entities/restaurant/provider%2Frestaurant%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
ID が「https://www.provider.com/restaurant/service/nr」であるサービス エンティティのサンプル エンドポイント:
DELETE v2/apps/delivery-provider-id/entities/service/provider%2Frestaurant%2Fservice%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
}
サブエンティティの削除
HTTP DELETE を使用して、最上位エンティティ内のサブエンティティ(メニュー内のメニュー項目など)を削除しないでください。代わりに、サブエンティティの削除は、関連リストまたは reverseReference からサブエンティティが削除された最上位エンティティに対する更新として扱います。
API レスポンス コード
呼び出しが成功しても、それはフィードが有効または正しいということではなく、API 呼び出しが行われたことだけです。呼び出しに成功すると、HTTP レスポンス コード 200 とともに空のレスポンス本文が返されます。
{}
失敗すると、HTTP レスポンス コードは 200 ではなく、エラーの原因はレスポンスの本文に表示されます。
たとえば、ユーザーがエンベロープの「vertical」値を FAKE_VERTICAL
に設定すると、次のようなメッセージが表示されます。
{
"error": {
"code": 400,
"message": "Invalid value at 'entity.vertical' (TYPE_ENUM), \"FAKE_VERTICAL\"",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "entity.vertical",
"description": "Invalid value at 'entity.vertical' (TYPE_ENUM), \"FAKE_VERTICAL\""
}
]
}
]
}
}
コードサンプル
以下では、さまざまな言語での Incremental Update API の使用方法の例を示します。以下のサンプルでは Google 認証ライブラリを使用し、フィードは v1 在庫スキーマを使用することを前提としています。別の解決策については、サーバー間アプリケーションに OAuth 2.0 を使用するをご覧ください。
エンティティの更新
Node.js
このコードでは Node.js 用の Google 認証ライブラリを使用しています。
const {auth} = require('google-auth-library') const request = require('request'); // The service account client secret file downloaded from the Google Cloud Console const serviceAccountJson = require('./service-account.json') // entity.json is a file that contains the entity data in json format const entity = require('./entity.json') const ENTITY_ID = 'your/entity/id' const PROJECT_ID = 'type/your-project-id' /** * Get the authorization token using a service account. */ async function getAuthToken() { let client = auth.fromJSON(serviceAccountJson) client.scopes = ['https://www.googleapis.com/auth/assistant'] const tokens = await client.authorize() return tokens.access_token; } /** * Send an incremental update to update or add an entity */ async function updateEntity(entity) { const token = await getAuthToken() request.post({ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, url: `https://actions.googleapis.com/v2/apps/${PROJECT_ID}/entities:batchPush`, body: { requests: [ { entity: { data: JSON.stringify(entity) name: `apps/${PROJECT_ID}/entities/${ENTITY_ID}` } } ], vertical: 'FOODORDERING' }, json: true }, (err, res, body) => { if (err) { return console.log(err); } console.log(`Response: ${JSON.stringify(res)}`) }) } updateEntity(entity)
Python
このコードは Python 用の Google 認証ライブラリを使用します。
from google.oauth2 import service_account from google.auth.transport.requests import AuthorizedSession import json import urllib PROJECT_ID = 'your-project-id' ENTITY_ID = 'type/your/entity/id' ENDPOINT = 'https://actions.googleapis.com/v2/apps/%s/entities:batchPush' % ( PROJECT_ID) # service-account.json is the service account client secret file downloaded from the # Google Cloud Console credentials = service_account.Credentials.from_service_account_file( 'service-account.json') scoped_credentials = credentials.with_scopes( ['https://www.googleapis.com/auth/assistant']) authed_session = AuthorizedSession(scoped_credentials) # Retrieving the entity update_file = open("entity.json") #JSON file containing entity data in json format. data = update_file.read() entity = {} entity['data'] = data #entity JSON-LD serialized as string entity['name'] = 'apps/%s/entities/%s' % (PROJECT_ID, urllib.quote(ENTITY_ID, '') ) # Populating the request request = {} request['entity'] = entity requestArray = [request] # Populating the payload payload = {} payload['requests'] = requestArray payload['vertical'] = 'FOODORDERING' response = authed_session.post(ENDPOINT, json=payload) print(response.text) #if successful, will be '{}'
Java
このコードは Java 用の Google 認証ライブラリを使用しています。
private static final String PROJECT_ID = "your-project-id"; private static final String ENTITY_ID = "type/your-entity-id"; /** * Get the authorization token using a service account. */ private static String getAuthToken() { InputStream serviceAccountFile = Example.class.getClassLoader().getResourceAsStream("service-account.json"); ServiceAccountCredentials.Builder credentialsSimpleBuilder = ServiceAccountCredentials.fromStream(serviceAccountFile).toBuilder(); credentialsSimpleBuilder.setScopes(ImmutableList.of("https://www.googleapis.com/auth/assistant")); AccessToken accessToken = credentialsSimpleBuilder.build().refreshAccessToken(); return accessToken.getTokenValue(); } /** * Send an incremental update to update or add an entity. * @param entityId The id of the entity to update. * @param entity the json of the entity to be updated. */ public void updateEntity(String entityId, JSONObject data) { String authToken = getAuthToken(); String endpoint = String.format("https://actions.googleapis.com/v2/apps/%s/entities/:batchPush", PROJECT_ID); JSONObject entity = new JSONObject(); entity.put("data", data.toString()); entity.put("name", String.format("apps/%s/entities/%s", PROJECT_ID, URLEncoder.encode(ENTITY_ID, "UTF-8"))); JSONObject request = new JSONObject(); request.put("entity", entity); JSONArray requestArray = new JSONArray(); requestArray.put(request); JSONObject payload = new JSONObject(); payload.put("requests", requestArray); payload.put("vertical", FOODORDERING); // Execute POST request executePostRequest(endpoint, authToken, payload); }
エンティティを削除する
Node.js
このコードでは Node.js 用の Google 認証ライブラリを使用しています。
const {auth} = require('google-auth-library') const request = require('request'); // The service account client secret file downloaded from the Google Cloud Console const serviceAccountJson = require('./service-account.json') // entity.json is a file that contains the entity data in json format const entity = require('./entity.json') const ENTITY_ID = 'restaurant/http://www.provider.com/somerestaurant' const PROJECT_ID = 'your-project-id' /** * Get the authorization token using a service account. */ async function getAuthToken() { let client = auth.fromJSON(serviceAccountJson) client.scopes = ['https://www.googleapis.com/auth/assistant'] const tokens = await client.authorize() return tokens.access_token; } /** * Send an incremental update to delete an entity */ async function deleteEntity(entityId) { const token = await getAuthToken() request.delete({ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, url: `https://actions.googleapis.com/v2/apps/${PROJECT_ID}/entities/${encodeURIComponent(entityId)}?entity.vertical=FOODORDERING`, body: {}, json: true }, (err, res, body) => { if (err) { return console.log(err); } console.log(`Response: ${JSON.stringify(res)}`) }) } deleteEntity(ENTITY_ID)
Python
このコードは Python 用の Google 認証ライブラリを使用します。
from google.oauth2 import service_account from google.auth.transport.requests import AuthorizedSession import json import urllib # Service config PROJECT_ID = 'your-project-id' ENTITY_ID = 'restaurant/http://www.provider.com/somerestaurant' DELETE_TIME = '2018-04-07T14:30:00-07:00' ENDPOINT = 'https://actions.googleapis.com/v2/apps/%s/entities/%s?entity.vertical=FOODORDERING&delete_time=%s' % ( PROJECT_ID, urllib.quote(ENTITY_ID, ''), urllib.quote(DELETE_TIME, '')) # service-account.json is the service account client secret file downloaded from the # Google Cloud Console credentials = service_account.Credentials.from_service_account_file( 'service-account.json') scoped_credentials = credentials.with_scopes( ['https://www.googleapis.com/auth/assistant']) authed_session = AuthorizedSession(scoped_credentials) response = authed_session.delete(ENDPOINT) print(response.text) #if successful, will be '{}'
Java
このコードは Java 用の Google 認証ライブラリを使用しています。
private static final String PROJECT_ID = "your-project-id"; private static final String ENTITY_ID = "restaurant/http://www.provider.com/somerestaurant"; /** * Get the authorization token using a service account. */ private static String getAuthToken() { InputStream serviceAccountFile = Example.class.getClassLoader().getResourceAsStream("service-account.json"); ServiceAccountCredentials.Builder credentialsSimpleBuilder = ServiceAccountCredentials.fromStream(serviceAccountFile).toBuilder(); credentialsSimpleBuilder.setScopes(ImmutableList.of("https://www.googleapis.com/auth/assistant")); AccessToken accessToken = credentialsSimpleBuilder.build().refreshAccessToken(); return accessToken.getTokenValue(); } /** * Send an incremental update to delete an entity. * @param entityId The id of the entity to delete. */ public void deleteEntity(String entityId) { String authToken = getAuthToken(); String endpoint = String.format( "https://actions.googleapis.com/v2/apps/%s/entities/%s?entity.vertical=FOODORDERING", PROJECT_ID, URLEncoder.encode(entityId, "UTF-8")); // Execute DELETE request System.out.println(executeDeleteRequest(endpoint, authToken)); }
ユースケース
増分更新、完全なフィード更新、API 呼び出しにおけるコンテンツの概要の例を以下に示します。
シナリオ | 更新するエンティティ | 説明と効果 |
---|---|---|
サービスの無効化 | Service |
予期せぬ理由でサービスを無効にする必要がある場合。 増分アップデート: 完全フィード: Google が次にフェッチする前に、完全フィードのエンティティを更新して、 |
特定の商品が在庫切れである | MenuItemOffer |
増分アップデート: 指定された MenuItem に対して inventoryLevel を 0 に設定し、他のすべてのデータを変更せずに、カプセル化している MenuItemOffer エンティティを送信します。 |
メニュー アイテムの価格変更 | MenuItemOffer |
増分更新: price を指定した MenuItem の更新価格に設定し、他のすべてのデータを変更せずに、カプセル化している MenuItemOffer エンティティを送信します。 |
新しい最上位エンティティを追加 タイプ |
Menu 、Restaurant 、Service |
たとえば、レストランに新しいメニューを追加する必要がある場合、 完全なフィード: データフィードにエンティティを追加し、バッチ取り込みを待ちます。 |
最上位エンティティを完全に削除する タイプ |
Menu 、Restaurant 、Service |
増分アップデート: 明示的な削除を送信します。 完全フィード: Google が次にフェッチする前に、全文フィードからエンティティを削除してください。削除しないと、エンティティは再度追加されます。 |
特定の Service で新しい配送地域を追加する |
ServiceArea |
増分フィード: 完全なフィードの場合と同様に、該当する ServiceArea エンティティの全フィールドをそのままにして、polygon 、geoRadius 、postalCode のいずれかに新しい配信地域を指定して送信します。 |
Service の到着予定時刻を更新 |
ServiceHours |
増分フィード: フィードの場合と同様に ServiceHours を送信しますが、leadTimeMin はそれに応じて更新されます。 |
「Service 」の配送価格を更新してください |
Fee |
増分フィード: price を更新して完全な配信 Fee を送信します。 |
Service の宅配またはテイクアウトの営業時間を更新してください |
ServiceHours |
増分フィード: フィードの場合と同様に ServiceHours を送信します。ただし、opens と closes プロパティは適宜更新されます。 |
Service (最低注文額の変更) |
Fee |
増分フィード: minPrice を更新して完全な Fee を送信します。 |
MenuItem を完全に削除する |
Menu |
増分フィード: parentMenuSectionId を空にして、フィードと同様に MenuItem を送信します。 |
バッチジョブと増分更新の処理時間に関する SLO
バッチで更新または削除されたエンティティは、ベスト エフォート モードで 2 時間以内に処理されますが、増分更新で更新されたエンティティは 5 分で処理されます。古いエンティティは 7 日後に削除されます。
次のどちらかを Google に送信できます。
- 在庫を最新の状態に保つために 1 日に複数のバッチジョブを使用する。または
- 1 日に 1 つのバッチジョブと増分 API を使用して在庫を最新の状態に保つ