v2 增量商品目录更新

本部分介绍了如何将商品目录实体的时效性更新发送给 Google。借助增量更新 API,您可以近乎实时地推送更新以及删除沙盒或生产清单中的实体。

此功能主要用于您无法预见的更新,例如紧急关闭。一般来讲,通过增量更新 API 提交的任何更改都应在一小时内生效。如果您的更改不需要立即体现,可以改用批量提取。增量更新会在五分钟内处理完毕。

前提条件

在实现增量更新之前,需要具备以下各项:

  1. 使用 Action 项目的 Editor 角色创建了一个服务帐号。如需了解详情,请参阅创建和设置项目
  2. 生产或沙盒数据 Feed 由 Google 托管和注入。如需了解详情,请参阅批量提取
  3. (可选,但建议执行)以您选择的语言安装 Google 客户端库,以便在调用 API 时便于使用 OAuth 2.0。以下代码示例使用了这些库。否则,您需要手动处理令牌交换,如使用 OAuth 2.0 访问 Google API 中所述。

Endpoints

在以下请求中,替换以下内容:

  • PROJECT_ID:与您在创建和设置项目中创建的项目的 Google Cloud 项目 ID。
  • TYPE:您要更新的数据 Feed 中的实体的实体类型(@type 属性)。
  • ENTITY_ID(仅限删除端点):要删除的实体的 ID。请务必对实体 ID 进行网址编码。
  • DELETE_TIME(仅限删除端点):可选字段,用于指示系统上删除实体的时间(默认为收到请求的时间)。时间值不能是将来的时间。通过增量调用发送实体时,实体版本控制还会使用 delete_time 字段来执行删除调用。将此值的格式设置为 yyyy-mm-ddTHH:mm:ssZ

更新端点

如需修改实体,请向以下端点发出 HTTP POST 请求,并包含更新和添加载荷。在一次 API 调用中,您最多可以更新 1000 个实体。

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

例如,要从 ID 为“菜单版块_122”的“菜单部分”实体从您的“交付提供方 ID”项目中删除,您需要对以下网址执行 HTTP DELETE API 调用:

https://actions.googleapis.com/v2/apps/delivery-provider-id/entities/MenuSection/menuSection_122?entity.vertical=FOODORDERING

沙盒环境

如需在沙盒商品目录中使用增量更新 API,请按照上述 Endpoint 中的说明操作,但请向 /v2/sandbox/apps/(而不是 /v2/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 应该与批处理 Feed 中的相同,但存在以下差异:

  • 载荷正文的大小不应超过 5 MB。与批量 Feed 类似,我们建议您去除空格以适应更多数据。
  • 信封如下所示:
{
  "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 文件。

假设某个批处理 Feed 如下所示:

{
  "@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:更新多个餐馆

如需在单个 API 调用中更新两个餐馆实体,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,并且 Feed 使用 v1 商品目录架构。

假设某个批处理 Feed 如下所示:

{
  "@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 商品目录架构中所述的批量 Feed 流程。

移除实体

如需移除顶级实体,请使用略微修改的端点,并在请求中使用 HTTP DELETE 而不是 HTTP POST。

删除顶级实体

假设您想要在 Feed 中删除一家餐馆。您还必须删除其服务和菜单。

具有 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 响应代码

成功的调用并不意味着 Feed 有效或正确,只是表示进行了 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\""
          }
        ]
      }
    ]
  }
}

代码示例

下面列举了一些示例来说明如何以各种语言使用增量更新 API。这些示例使用 Google Auth 库,并假设使用 v1 产品目录架构的 Feed。如需了解替代解决方案,请参阅针对服务器对服务器应用使用 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 调用中增量更新、完整 Feed 更新和大致内容的示例:

场景 要更新的实体 说明和效果
停用服务 Service

出于无法预知的原因,您需要停用服务。

增量更新:通过将相关 ServiceisDisabled 属性设置为 true 来更新该实体,但保持其他属性不变。

完整 Feed:请务必在 Google 下次提取之前更新完整 Feed 中的实体,使 isDisabled 设置为 true,否则实体将重新启用。

特定商品缺货 MenuItemOffer 增量更新:发送封装 MenuItemOffer 实体,其中给定 MenuIteminventoryLevel 设置为 0,并且所有其他数据保持不变。
菜单项价格变动 MenuItemOffer 增量更新:发送封装 MenuItemOffer 实体,其中 price 设置为给定 MenuItem 的更新价格,并且所有其他数据保持不变。

添加新的顶级实体

仅适用于 MenuRestaurantService 类型的实体。

MenuRestaurantService

例如,您需要向餐馆添加新菜单。

完整 Feed:在数据 Feed 中添加实体并等待批量提取。

永久删除顶级实体

仅适用于 MenuRestaurantService 类型的实体。

MenuRestaurantService

增量更新:发送显式删除

完整 Feed:请务必在 Google 下次提取之前从完整 Feed 中移除该实体,否则系统会重新添加该实体。

在特定Service中添加新的送货区域 ServiceArea 增量更新型 Feed:在正常情况下,在 polygongeoRadiuspostalCode 内指定新的送货区域,然后照常发送完整字段(其中包含完整 Feed)的所有相关字段。
更新Service的预计送达时间 ServiceHours 增量更新型 Feed:除了在 Feed 中更新 leadTimeMin 外,还应使用 Feed 中相同的方式发送 ServiceHours
更新Service的送货价格 Fee 增量更新型 Feed:发送完整投放 Fee 并更新 price
更新Service的送货或外卖时段 ServiceHours 增量更新型 Feed:除了在 Feed 中更新 openscloses 属性外,还应以更新 Feed 的方式发送 ServiceHours
Service(更改最低订单金额) Fee 增量更新型 Feed:发送完整的 Fee,并更新 minPrice
永久删除MenuItem Menu 增量更新型 Feed:与 Feed 中的相同,发送 MenuItem,但 parentMenuSectionId 为空。

批处理作业和增量更新的处理时间 SLO

通过批量更新或删除的实体将在 2 小时内以最佳方式进行处理,而通过增量更新方式更新的实体将在 5 分钟内得到处理。过时实体会在 7 天后被删除。

您可以向 Google 发送以下信息:

  • 每天进行多个批量作业,及时更新商品目录,或者
  • 每天一个批量作业和增量 API,确保您的商品目录保持最新状态。