本部分介绍了如何将对 Feed 的时效性更新发送给 Google。借助增量更新 API,您可以近乎实时地更新和删除 Feed 中的实体。
此功能主要用于您无法预见的更新,例如紧急关闭。一般来讲,通过增量更新 API 提交的任何更改都应在不超过一周的时间内生效。如果您的更改不需要立即反映,则可以改用批量更新。增量更新会在五分钟内处理完毕。
设置
如需实现增量更新,请执行以下操作:
- 按照创建和设置项目中所述的步骤创建项目。
- 按照设置服务帐号中所述的步骤创建服务帐号。请注意,您必须是项目的“所有者”,才能为服务帐号添加“编辑者”角色
- (可选,但建议执行)以您选择的语言安装 Google 客户端库,以便在调用 API 时便于使用 OAuth 2.0。以下代码示例使用了这些库。否则,您需要手动处理令牌交换,如使用 OAuth 2.0 访问 Google API 中所述。
端点
如需通知 Google 有更新,请向 Incremental Updates 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 产品目录架构。您想使用“实体部分”为“菜单”的餐厅实体,而实体 ID 为“菜单部分_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:删除顶级实体
设想一下,您想删除使用 v1 产品目录架构的 Feed 中的餐厅。您还必须删除其服务和菜单。
带有 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 库,并假设使用 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 = '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)); }
使用场景
以下用例是 API 调用中增量更新、完整 Feed 更新和大致内容的示例:
场景 | 顶级实体 | 说明和效果 |
---|---|---|
停用服务 | DisabledService |
出于无法预知的原因,您需要停用服务。 增量更新:将相关 完整 Feed:请务必在 Google 下次提取之前更新完整 Feed 中的实体,使 |
特定商品缺货 | Menu |
增量更新:发送封装 Menu 实体,其中给定 MenuItem 的 offer.inventoryLevel 设置为 0,并且所有其他数据保持不变。 |
菜单项价格变动 | Menu |
增量更新:发送封装 Menu 实体,其中 offer.price 设置为给定 MenuItem 的更新价格,并且所有其他数据保持不变。 |
添加新的顶级实体 仅适用于 |
Menu 、Restaurant 、Service |
例如,您需要向餐馆添加新菜单。 增量更新:发送新菜单实体及其字段 |
永久删除顶级实体 仅适用于 |
Menu 、Restaurant 、Service |
增量更新:发送显式删除。 完整 Feed:请务必在 Google 下次提取之前从完整 Feed 中移除该实体,否则系统会重新添加该实体。 |
在特定Service 中添加新的送货区域 |
Service |
增量更新型 Feed:在正常情况下,像在完整 Feed 中那样,将 Service 实体的所有字段完好无损,并在 Service 的 areaServed 内指定新的送货区域。 |
更新Service 的预计送达时间 |
Service |
增量更新型 Feed:除了在 Feed 中更新 hoursAvailable.deliveryHours 外,还应使用 Feed 中相同的方式发送 Service 。 |
更新Service 的送货价格 |
Service |
增量更新型 Feed:发送完整的 Service ,并更新 offers.priceSpecification.price 。 |
更新Service 的送货或外卖时段 |
Service |
增量更新型 Feed:除了在 Feed 中更新 hoursAvailable 外,还应使用 Feed 中相同的方式发送 Service 。 |
Service (更改最低订单金额) |
Service |
增量更新型 Feed:发送完整的 Service ,并更新 Service.offers.priceSpecification.eligibleTransactionVolume |
永久删除MenuItem |
Menu |
增量更新型 Feed:发送 Menu 的方式与 Feed 中相同,但这个 MenuItem 已从 hasMenuItems 列表中移除。 |
批处理作业和增量更新的处理时间 SLO
通过批量更新或增量更新添加的实体将在 1-2 天内得到处理。通过批量方式更新或删除的实体将在 2 小时内得到处理,而通过增量方式更新的实体将在 5 分钟内处理完毕。过时实体会在 7 天后被删除。
您可以向 Google 发送以下信息:
- 每天进行多个批量作业,及时更新商品目录,或者
- 每天一个批量作业和增量 API,确保您的商品目录保持最新状态。