字段掩码是一种供 API 调用方列出请求应返回或更新的字段的方式。使用 FieldMask 可让 API 避免不必要的工作,从而提高性能。字段掩码用于 Google 文档 API 中的读取和更新方法。
使用字段掩码进行读取
文档可能很大,而且通常您不需要读取请求返回的 Document
资源的每个部分。您可以使用 fields
网址参数限制在 Docs API 响应中返回的内容。为了获得最佳性能,请在回复中明确列出您需要的字段。
fields 参数的格式与 FieldMask 的 JSON 编码相同。 简而言之,多个不同的字段以英文逗号分隔,子字段以英文句点分隔。字段名称可以采用 camelCase 或 separated_by_underscores 格式指定。为方便起见,同一类型的多个子字段可以列在圆括号内。
以下 documents.get
请求示例使用 title,tabs(documentTab(body.content(paragraph))),revisionId
的字段掩码来提取文档的 title
、Body
对象(来自所有标签页)的 Paragraph
以及文档内的文档的 revisionId
:
GET https://docs.googleapis.com/v1/documents/documentId?fields=title,tabs(documentTab(body.content(paragraph))),revisionId
此方法调用的响应是一个 Document
对象,其中包含字段掩码中请求的组件:
{ "title": "TITLE
", "revisionId": "REVISION_ID
", "tabs": [ { "documentTab": { "body": { "content": [ {}, { "paragraph": { "elements": [ { "startIndex": 1, "endIndex": 59, "textRun": { "content": "CONTENT
", "textStyle": {} } } ], "paragraphStyle": { "namedStyleType": "NORMAL_TEXT", "direction": "LEFT_TO_RIGHT" } } } ] } } } ] }
使用字段掩码进行更新
有时,您只需要更新对象中的某些字段,而让其他字段保持不变。documents.batchUpdate
操作中的更新请求使用字段掩码来告知 API 正在更改哪些字段。更新请求会忽略字段掩码中未指定的任何字段,并使用其当前值。
您还可以通过不在更新后的消息中指定某个字段,但将该字段添加到掩码中,来取消设置该字段。此操作会清除相应字段之前具有的任何值。
更新字段掩码的语法与读取字段掩码的语法相同。
以下示例使用 UpdateTextStyleRequest
将文档中 range
5–20 的“Google Docs API”一词设置为粗体:
POST https://docs.googleapis.com/v1/documents/documentId:batchUpdate
{ "title": "TITLE
", "revisionId": "REVISION_ID
", "suggestionsViewMode": "SUGGESTIONS_INLINE", "documentId": "DOCUMENT_ID
", "tabs": [ { "documentTab": { "body": { "content": [ { "endIndex": 1, "sectionBreak": { "sectionStyle": { "columnSeparatorStyle": "NONE", "contentDirection": "LEFT_TO_RIGHT", "sectionType": "CONTINUOUS" } } }, { "startIndex": 1, "endIndex": 59, "paragraph": { "elements": [ { "startIndex": 1, "endIndex": 5, "textRun": { "content": "CONTENT
", "textStyle": {} } }, { "startIndex": 5, "endIndex": 20, "textRun": { "content": "CONTENT
", "textStyle": { "bold": true } } }, { "startIndex": 20, "endIndex": 59, "textRun": { "content": "CONTENT
", "textStyle": {} } } ], "paragraphStyle": { "namedStyleType": "NORMAL_TEXT", "direction": "LEFT_TO_RIGHT" } } } ] }, { ... // style details }, } } ], }