v2 增量库存更新

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

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

前提条件

在实现增量更新之前,必须具备以下几项:

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

端点

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

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

更新端点

如需修改实体,请向以下端点发出 HTTP POST 请求,并在其中包含更新和新增内容的载荷。在一次 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

沙盒环境

如需在沙盒目录中使用 增量更新 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 库,并假设 Feed 使用 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));
}

用例

以下用例是增量更新、完整 Feed 更新和 API 调用概要内容的示例:

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

您需要因意外原因停用服务。

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

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

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

添加新的顶级实体

仅适用于 MenuRestaurantService 类型的实体。

MenuRestaurantService

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

完整 Feed:在数据 Feed 中添加实体,然后等待批量注入。

永久删除顶级实体

仅适用于 MenuRestaurantService 类型的实体。

MenuRestaurantService

增量更新:发送显式删除

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

在特定的Service添加新的送货区域 ServiceArea 增量 Feed:发送相关 ServiceArea 实体时,请确保其所有字段都保持完好,就像您在完整 Feed 中通常的操作一样,并在 polygongeoRadiuspostalCode 中指定新的送货区域。
更新Service的预计送达时间 ServiceHours 增量更新 Feed:发送 ServiceHours 的方法与在 Feed 中发送相同的,不同之处在于其 leadTimeMin 会进行相应的更新。
更新Service的运费 Fee 增量 Feed:在更新 price 的情况下发送完整传送 Fee
请在Service中更新送货或外卖时段 ServiceHours 增量更新 Feed:发送 ServiceHours 的方法与在 Feed 中相同,只是它的 openscloses 属性会相应更新。
Service(更改最低订单金额) Fee 增量 Feed:发送完整的 Fee 并更新 minPrice
永久删除MenuItem Menu 增量更新 Feed:发送 MenuItem 的方法与在 Feed 中发送一样,但需将 parentMenuSectionId 留空。

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

通过批量更新或删除的实体将在 2 小时内以“尽力而为”模式处理,而通过增量更新更新的实体将在 5 分钟内处理。系统会在 7 天后删除过时的实体。

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

  • 每天执行多个批量作业,让您的库存保持最新状态,或者
  • 每天处理一个批量作业,并采用增量 API,使您的库存保持最新状态。