本部分介绍如何向 Google 发送具有时效性的 Feed 更新。借助 增量更新 API,您可以近乎实时地更新和删除 Feed 中的实体。
此功能主要用于您无法预见的更新,例如紧急关闭。一般来说,通过 增量更新 API 提交的任何更改都应在不超过一周的时间内生效。如果您的更改不需要立即体现,您可以改用批量更新。增量更新的处理时间不超过 5 分钟。
初始设置
如需实现增量更新,请执行以下操作:
- 按照创建和设置项目中列出的步骤来创建项目。
- 按照设置服务帐号中所述的步骤创建服务帐号。请注意,您必须是项目的“Owner”,才能为服务帐号添加“Editor”角色
- (可选但建议执行的操作)使用您选择的语言安装 Google 客户端库,以便在调用 API 时方便使用 OAuth 2.0。下面提供的代码示例使用了这些库。否则,您需要按照使用 OAuth 2.0 访问 Google API 中的说明手动处理令牌交换。
端点
如需通知 Google 有更新,请向增量更新 API 发出 HTTP POST 请求,并在其中包含更新和新增内容的载荷。您所使用的目录架构决定了您向哪个端点发送请求:
v2 广告资源
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/TYPE/ENTITY_ID:push
v1 广告资源
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/ENTITY_ID:push
如需移除实体,请向与您所使用的目录架构相对应的以下端点发出 HTTP DELETE 请求:
v2 广告资源
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/TYPE/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
v1 广告资源
https://actions.googleapis.com/v2/apps/PROJECT_ID/entities/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
在上述请求中,替换以下内容:
- PROJECT_ID:与您在创建和设置项目中创建的项目关联的 Google Cloud 项目 ID。
- TYPE(仅限 v2 产品目录架构):要更新的数据 Feed 中对象的实体类型(
@type
属性)。 - ENTITY_ID:载荷中包含的实体的 ID。请务必对您的实体 ID 进行网址编码。
- DELETE_TIME(仅限删除端点):可选字段,表示在系统上删除实体的时间(默认是收到请求的时间)。时间值不能是将来的时间。通过增量调用发送实体时,实体版本控制也会在删除调用的情况下使用
delete_time
字段。请将此值的格式设置为yyyy-mm-ddTHH:mm:ssZ
例如,您有一个 ID 为“delivery-provider-id”的项目,其使用 v2 目录架构。您想要更改餐厅实体类型为“MenuSection”且实体 ID 为“menuSection_122”的餐厅。用于更新数据的端点将如下所示:
https://actions.googleapis.com/v2/apps/delivery-provider-id/entities/MenuSection/menuSection_122:push
如需移除同一实体,您需要进行以下 HTTP DELETE API 调用:
https://actions.googleapis.com/v2/apps/delivery-provider-id/entities/MenuSection/menuSection_122?entity.vertical=FOODORDERING
沙盒请求
对于沙盒请求,请遵循上述端点中的指南,但请向 /v2/sandbox/apps/
而非 /v2/apps/
发出请求。例如,针对 v2 目录架构的沙盒删除请求的结构如下:
https://actions.googleapis.com/v2/sandbox/apps/PROJECT_ID/entities/TYPE/ENTITY_ID?entity.vertical=FOODORDERING&delete_time=DELETE_TIME
更新和增补项
您的每日批量 Feed 也应包含通过此 API 提交的任何更改。否则,批量更新会覆盖增量更改。
载荷
每个 POST 请求都必须包含请求参数,以及包含商品目录架构中列出的任何实体类型的结构化数据的 JSON 载荷。
JSON 应与其在批量 Feed 中显示相同,但存在以下差异:
- 载荷正文的大小不得超过 5 MB。与批量 Feed 类似,我们建议您删除空格,以便存放更多数据。
- 信封如下所示:
{ "entity": { "data":"ENTITY_DATA", "vertical":"FOODORDERING" }, "update_time":"UPDATE_TIMESTAMP" }
在上述载荷中,替换以下内容:
- 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/apps/provider-project/entities/Restaurant/restaurant12345:push Host: actions.googleapis.com Content-Type: application/ld+json { "entity": { "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 一样,您的更新必须包含整个顶级实体(菜单)的 JSON,并且 Feed 使用 v1 目录架构。
请考虑如下所示的批量 Feed:
{ "@type": "MenuItemOffer", "@id": "menuitemoffer6680262", "sku": "offer-cola", "menuItemId": "menuitem896532", "price": 3.00, "priceCurrency": "USD" }
那么,通过 POST 进行的增量更新将如下所示:
POST v2/apps/provider-project/entities/MenuItemOffer/menuitemoffer6680262:push Host: actions.googleapis.com Content-Type: application/ld+json { "entity": { "data": { "@type": "MenuItemOffer", "@id": "menuitemoffer6680262", "sku": "offer-cola", "menuItemId": "menuitem896532", "price": 1.00, "priceCurrency": "USD" }, "vertical": "FOODORDERING" } }
添加实体
如需添加实体,请避免使用目录更新。而是应该按照 v2 目录架构中所述的方式使用批量 Feed 流程。
移除实体
如需移除顶级实体,请在请求中使用稍加修改的端点,并使用 HTTP DELETE 而不是 HTTP POST。
请勿使用 HTTP DELETE 移除顶级实体中的子实体(例如菜单中的菜单项)。而应将移除子实体视为对顶级实体的更新,即从相关列表或参数中移除子实体。
示例 1:删除顶级实体
假设您想要删除 Feed 中使用 v1 产品目录架构的餐馆。您还必须删除其服务和菜单。
一个 ID 为“https://www.provider.com/restaurant/menu/nr”的菜单实体的示例端点:
DELETE v2/apps/delivery-provider-id/entities/https%3A%2F%2Fwww.provider.com%2Frestaurant%2Fmenu%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
餐厅实体 ID 为“https://www.provider.com/restaurant/nr”的示例端点:
DELETE v2/apps/delivery-provider-id/entities/https%3A%2F%2Fwww.provider.com%2Frestaurant%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
以下是 ID 为“https://www.provider.com/restaurant/service/nr”的服务实体的示例端点:
DELETE v2/apps/delivery-provider-id/entities/https%3A%2F%2Fwww.provider.com%2Frestaurant%2Fservice%2Fnr?entity.vertical=FOODORDERING
Host: actions.googleapis.com
}
示例 2:移除子实体
要从顶级实体中移除子实体,您应发送顶级实体,并从相应字段中移除该子实体。以下示例假定 Feed 使用 v1 目录架构。
例如,如需移除某个服务区域,请使用从 areaServed
列表中移除的服务区域来更新该服务。
POST v2/apps/delivery-provider-id/entities/https%3A%2F%2Fwww.provider.com%2Frestaurant%2Fservice%2Fnr:push
Host: actions.googleapis.com
Content-Type: application/ld+json
{
"entity": {
// Note: "data" is not serialized as a string in our example for readability.
"data": {
"@type": "Service",
"provider": {
"@type": "Restaurant",
"@id": "https://www.provider.com/restaurant/nr"
},
"areaServed": [
{
"@type": "GeoCircle",
"geoMidpoint": {
"@type": "GeoCoordinates",
"latitude": "42.362757",
"longitude": "-71.087109"
},
"geoRadius": "10000"
}
// area2 is removed.
]
...
},
"vertical": "FOODORDERING"
}
}
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 = '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 update or add an entity */ async function updateEntity(entityId, 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/${encodeURIComponent(entityId)}:push`, body: { entity: { data: JSON.stringify(entity), vertical: 'FOODORDERING', } }, json: true }, (err, res, body) => { if (err) { return console.log(err); } console.log(`Response: ${JSON.stringify(res)}`) }) } updateEntity(ENTITY_ID, 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 = 'restaurant/http://www.provider.com/somerestaurant' ENDPOINT = 'https://actions.googleapis.com/v2/apps/%s/entities/%s:push' % ( PROJECT_ID, urllib.quote(ENTITY_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() # Populating the entity with wrapper entity = {} entity['data'] = data #entity JSON-LD serialized as string entity['vertical'] = 'FOODORDERING' request = {} request['entity'] = entity response = authed_session.post(ENDPOINT, json=request) 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 = "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 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 entity) { String authToken = getAuthToken(); String endpoint = String.format( "https://actions.googleapis.com/v2/apps/%s/entities/%s:push", PROJECT_ID, URLEncoder.encode(entityId, "UTF-8")); JSONObject data = new JSONObject(); data.put("data", entity.toString()); data.put("vertical", "FOODORDERING"); JSONObject jsonBody = new JSONObject(); jsonBody.put("entity", data); // Execute POST request executePostRequest(endpoint, authToken, jsonBody); }
移除实体
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 调用概要内容的示例:
场景 | 顶级实体 | 说明和效果 |
---|---|---|
停用服务 | DisabledService |
您需要因意外原因停用服务。 增量更新:发送相关 完整 Feed:请务必更新完整 Feed 中的实体,将 |
特定商品缺货 | Menu |
增量更新:发送封装 Menu 实体,对于给定的 MenuItem ,将 offer.inventoryLevel 设置为 0,所有其他数据保持不变。 |
菜品价格变动 | Menu |
增量更新:发送封装 Menu 实体,其中 offer.price 设为给定 MenuItem 的更新价格,所有其他数据保持不变。 |
添加新的顶级实体 仅适用于 |
Menu 、Restaurant 、Service |
例如,您需要为餐馆添加新菜单。 增量更新:发送新的菜单实体以及其字段 |
永久删除顶级实体 仅适用于 |
Menu 、Restaurant 、Service |
增量更新:发送显式删除。 完整 Feed:确保在 Google 下次提取之前从完整 Feed 中移除实体,否则系统会重新添加该实体。 |
在特定的Service 添加新的送货区域 |
Service |
增量 Feed:发送相关 Service 实体时,请确保其所有字段都保持完好,就像您通常在完整 Feed 中一样,并在 Service 的 areaServed 内指定新的送货区域。 |
更新Service 的预计送达时间 |
Service |
增量更新 Feed:发送 Service 的方法与在 Feed 中发送相同的,不同之处在于其 hoursAvailable.deliveryHours 会进行相应的更新。 |
更新Service 的运费 |
Service |
增量 Feed:发送完整的 Service 并更新 offers.priceSpecification.price 。 |
请在Service 中更新送货或外卖时段 |
Service |
增量更新 Feed:发送 Service 的方法与在 Feed 中发送相同的,不同之处在于其 hoursAvailable 会进行相应的更新。 |
Service (更改最低订单金额) |
Service |
增量 Feed:发送完整的 Service 并更新 Service.offers.priceSpecification.eligibleTransactionVolume |
永久删除“MenuItem ” |
Menu |
增量更新 Feed:按照与在 Feed 中相同的方式发送 Menu ,但需从 hasMenuItems 列表中移除此 MenuItem 。 |
关于批量作业和增量更新的处理时间的 SLO
通过批量更新或增量更新添加的实体将在 1-2 天内得到处理。通过批量更新或删除的实体将在 2 小时内处理,而通过增量更新更新的实体则需要 5 分钟。系统会在 7 天后删除过时的实体。
您可以发送以下信息给 Google:
- 每天执行多个批量作业,让您的库存保持最新状态,或者
- 每天处理一个批量作业,并采用增量 API,使您的库存保持最新状态。